python --經常使用內置模塊01

一、簡單瞭解模塊
        模塊就是咱們把裝有特定功能的代碼進行歸類的解構,從代碼編寫的單位來看咱們的程序
從小到大的順序:一條代碼< 語句塊<代碼塊(函數,類) < 模塊
咱們目前寫的全部py文件都是模塊,還有一些內置的模塊
引入模塊
# from XXX import XXXX
# from school import student # 導入一個具體的功能
# import school # 導入整個模塊

import random
print(random.randint(10,20))

from random import randint
print(randint(10,20))
   
  二、random模塊
   全部關於隨機相關的內容都在random模塊中
      random主要是和隨機相關的內容
       
random()  隨機小數
uninform(a,b) 隨機小數
randint(a,b)  隨機整數
choice() 隨機選擇一個
sample()隨機選擇多個
shuffle() 打亂

  

import random

print(random.randint(10,20))  # 隨機整數
print(random.randrange(1,10,2))  # 1-10的奇數[1,10)
print(random.random())  # python中全部隨機數的根  隨機小數 0-1

print(random.uniform(10,20)) # 10-20的隨機小數
lst = ['蘋果','香蕉','荔枝','草莓','竹馬']
random.shuffle(lst)  # 隨機打亂順序
print(lst)

# 從列表中隨機選一個
print(random.choice(['蘋果','香蕉','荔枝','草莓','竹馬']))
print(random.sample(['蘋果','香蕉','荔枝','草莓','竹馬'],3))
 
三、Collections
 
   collections 模塊主要封裝了一些關於集合類的相關操做。例:Iterable,Iterator,還有出了基本數據類型之外的數據集合類型, Counter,deque,OrderDict,default以及namedtuple
 
  一、counter()計數器
from collections import Counter
print(Counter('中心廣場的中心的公共的場所'))
lst = ['蘋果','蘋果','香蕉','','荔枝','芒果']
print(Counter(lst))
# Counter({'蘋果': 2, '香蕉': 1, '梨': 1, '荔枝': 1, '芒果': 1})

  二、defaultdic() 默認值字典,能夠給字典設置默認值,當key不存在的時候,直接獲取默認值 python

from collections import defaultdict

# 默認值字典
d = defaultdict(lambda:0)  # callable 可調用的,字典是空的
print(d)  # defaultdict(<function <lambda> at 0x00000183A97B1E18>, {})
print(d['zhangmeng']) # 從字典往外拿數據,字典是空的  key:callable()
print(d['sunqian']) # 這裏的[]和get()不是一回事
print(d)
# defaultdict(<function <lambda> at 0x000001AD70AD1E18>, {'zhangmeng': 0, 'sunqian': 0})

  三、OrderDic()有序字典數據庫

from collections import OrderedDict
dic = OrderedDict() # 有序字典
dic['a'] = 'A'
dic['b'] = 'B'
print(dic)  # OrderedDict([('a', 'A'), ('b', 'B')])
print(dic.get('a'))
print(dic.values())  # odict_values(['A', 'B'])
print(dic["a"])
  四、deque 雙向隊列
 
          數據結構:
 
                一、棧:FILO 先進後出 --》砌牆的磚頭,蒸饅頭
                二、隊列:FIFO 先進先出 --》排隊
#
# 因爲python沒有給出Stack模塊.因此咱們本身手動寫一個粗略版本
# (注意, 此版本有嚴重的併發問題)
# 特色:先進後出
class StackFullException(Exception):
    pass

class StackEmptyException(Exception):
    pass

class Stack:

    def __init__(self,size):
        self.size = size
        self.lst = [] #存放數據的列表
        self.top = 0 # 棧頂指針

    # 入棧
    def push(self,el):
        if self.top >= self.size:
            raise StackFullException("your stack is full!!")
        self.lst.insert(self.top,el) #放元素
        self.top +=1 # 棧頂指針向上移動一下

# 出棧
    def pop(self):
        if self.top == 0:
            raise StackEmptyException("your stack is empty!!")
        self.top -= 1
        el = self.lst[self.top]
        return el

s =Stack(6)

s.push('sunny')
s.push('ANNA')
s.push('zhouyou')
s.push('hutong')
s.push('wangying')
s.push('zhangmeng')

print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
# print(s.pop())

隊列:python提供了queue模塊數據結構

import queue
q = queue.Queue()
q.put('a1')
q.put('a2')
q.put('a3')
q.put('a4')
q.put('a5')
q.put('a6')
q.put('a7')
q.put('a8')

print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
隊列
注:若是隊列中沒有元素了,再去拿元素,此時程序會阻塞
 
collections 中的deque
from collections import deque

d = deque() # 建立雙向隊列
d.append("認識")
d.append("人生")
d.append("想象")
d.append("心門")
d.appendleft("週末")  # 從左邊添加
d.appendleft("週四")
d.appendleft("週一")
d.appendleft("週二")

print(d.pop())  # 從右邊拿數據
print(d.pop())  # 從右邊拿數據
print(d.pop())  # 從右邊拿數據
print(d.pop())  # 從右邊拿數據
print(d.popleft())  # 從左邊拿數據
print(d.popleft())  # 從左邊拿數據
print(d.popleft())  # 從左邊拿數據
print(d.popleft())  # 從左邊拿數據
deque
 
四、Time模塊
 
    時間有三種:
        結構化時間  gmtime()  localtime()
        時間戳  time.time()  time.mktime()
        格式化時間 time.strftime()time.strptime()
import time
# 時間戳 :從1970-01-01 00:00:00 開始計算,將來存儲的時候用的是時間戳
print(time.time())
# print(time.mktime())

# 格式化時間
print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 通常用來顯示
# print(time.strptime('%Y-%m-%d %H:%M:%S'))
# 結構化時間(python時間)
print(time.localtime())  # 本地化的東八區時間
# time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, tm_hour=21, tm_min=5, tm_sec=30, tm_wday=2, tm_yday=360, tm_isdst=0)
print(time.gmtime()) # 格林尼治時間
t = time.localtime()
print(t.tm_year)
print(t.tm_mon)
print(t.tm_min)
View Code

時間格式化的標準併發

%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鐘數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天爲星期的開始
%w 星期(0-6),星期天爲星期的開始
%W 一年中的星期數(00-53)星期一爲星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號自己

  

  時間轉化:
                數字 -->字符串
                struct_time = time.location(數字)
                str = time.strftime("格式",struct_time)
# 數據庫中存儲一個數字,把他還原成咱們的格式化時間
a = 0
# 先把這個時間戳轉化成python中的解構化時間
t = time.localtime(a)
# t = time.gmtime(a) # 格林尼治時間
# 把一個結構化時間轉化成格式化時間
s = time.strftime('%Y-%m-%d %H:%M:%S',t)
print(s)
      字符串 -->數字
                struct_time = time.strptime(字符串,"格式")
                num = time.mktime(struct_time)
# 讓用戶輸入一個時間,把這個時間轉化成時間戳
user_input = input("請輸入一個時間:")
# 把用戶輸入的字符串轉化成格式化時間
struct_time = time.strptime(user_input,"%Y-%m-%d %H:%M:%D") # p :parse
# 轉化成時間戳
num = time.mktime(struct_time)
print(num)

    計算時間差app

# 輸入兩個時間,計算兩個時間之間的時間差
import time
first_time= input('請輸入第一個時間:')
second_time = input('請輸入第二個時間:')
time1 = time.mktime(time.strptime(first_time,'%Y-%m-%d %H:%M:%S'))
time2 = time.mktime(time.strptime(second_time,'%Y-%m-%d %H:%M:%S'))
time_cha = abs(time1-time2)
struct_time = time.localtime(time_cha)
print(struct_time)
print(f"過去了{struct_time.tm_year - 1970}年{struct_time.tm_mon - 1}月{struct_time.tm_mday-1}日{struct_time.tm_hour}時{struct_time.tm_min}分{struct_time.tm_sec}秒")
 
五、functools
 
      wraps  給裝飾器中的inner更名字
from functools import wraps

def wrapper(fn):
    @wraps(fn) # 把inner的名字改爲原來的func
    def inner(*args,**kwargs):
        print("")
        ret = fn(*args,**kwargs)
        print("")
        return ret
    return inner

@wrapper # func = wrapper(func)
def func():
    print('hhhh')

print(func.__name__)

# 不加@wraps 時結果爲 inner
# 加@wraps 時結果爲func

      reduce 概括dom

# map 映射 reduce 概括
print(list(map(lambda x : x**2, [i for i in range(10)])))

from functools import reduce

def func(a,b):
    return a + b  # 累加

#會把咱們每個數據交給func去執行,把默認值做爲第一個參數傳遞給函數
# 第二個參數就是你這個序列中的第一個數據
# 接下來,把剛纔返回的結果做爲第一個參數傳遞給a
# 繼續把剛纔的結果給第一個參數,把第三個數據傳遞給b
ret = reduce(func,[1,4,7,2,8,5,6])
# 工做流程
func(func(func(0,1),4),7)
print(ret)
print(reduce(lambda x,y :x+y,[i for i in range(101)]))

      偏函數  把函數的參數固定 ide

from functools import partial

def eat(zhushi,fushi):
    print(zhushi,fushi)

# 固定函數中某些參數的值
eat2 = partial(eat,fushi = '冒菜')
eat2("大米飯")
eat2("小米飯")
eat2("黑米飯")
eat2("紫米飯")
eat2("糯米飯")
相關文章
相關標籤/搜索