9.python標準庫

#-*- coding: utf-8 -*-

print("================time標準庫================")
#time庫 python處理時間的標準庫
#獲取現在時間  time.localtime()
#獲取UTC世界統一時間 time.gmtime   北京時間比統一時間早8個小時
import time
t_local = time.localtime()
t_UTC = time.gmtime()
print("t_local",t_local) #本地時間
print("t_UTC",t_UTC) #UTC統一時間
print(time.ctime()) #返回本地時間的字符串

#時間戳與計時器
#time.time() 返回自紀元以來的秒數,記錄sleep
#time.perf_counter() 隨意選取一個時間點,記錄現在時間到該時間點間隔秒數,記錄 sleep
#time.process_time() 隨意選取一個時間點,記錄現在時間到該時間點間隔秒數,不記錄 sleep
#perf_counter()精度比time()更高一些
t_1_start = time.time()
t_2_start = time.perf_counter()
t_3_start = time.process_time()
print(t_1_start)
print(t_2_start)
print(t_3_start)
#時間格式化輸出 time.triftime 自定義格式化輸出
lctime = time.localtime()
print(time.strftime("%Y-%m-%d %A %H:%M:%S",lctime))
#睡眠
time.sleep(1)

print("================random標準庫==============")
#python通過random庫提供各種僞隨機數
#隨機種子 -- seed(a=None)
#相同種子會產生相同隨機數,如果不設置隨機種子,以系統當前時間爲默認值
from random import *
seed(10)
print(random())
seed(10)
print(random())
#產生隨機整數
#randint(a,b) -- 產生[a,b]之間的隨機整數
numbers = [randint(1,10) for i in range(10)]
print(numbers)
#randrange(a) -- 產生[0,a)之間的隨機整數,不包含a
numbers = [randrange(10) for i in range(10)]
print(numbers)
#randrange(a,b,step) -- 產生[a,b)之間以step爲步長的隨機整數
numbers = [randrange(0,10,2) for i in range(10)]
print(numbers)
#產生隨機浮點數
#random()--產生[0.0,1.0]之間的隨機浮點數
numbers = [random() for i in range(10)]
print(numbers)
#uniform(a,b)-- 產生[a,b]之間的隨機浮點數
numbers = [uniform(2.1,3.5) for i in range(10)]
print(numbers)
#序列用函數
#choice(seq)--從序列類型中隨機返回一個元素
print(choice(['win','lose','draw']))
print("python")
#choices(seq,weights=None,k) --對序列類型進行k次重複採樣,可設置權重
#重複採樣5次,取完之後放回再取
print(choices(['win','lose','draw'],k=5))
#可對每個元素設置權重
print(choices(['win','lose','draw'],[4,4,2],k=10))
#shuffle(seq) 將序列類型中元素隨機排列,返回打亂後對序列
numbers = ["one","two","three","four"]
shuffle(numbers)
print(numbers)
#sample(pop,k) -- 從pop類型中隨機取k個元素,以列表類型返回
print(sample([10,20,30,40,50],k=3))
#概率分佈  以高斯分佈爲例
#gauss(mean,std) 生產一個符合高斯分佈的隨機數 mean是均值 std是標準差
number = gauss(0,1)
print(number)
#多生成幾個畫直方圖顯示
import matplotlib.pyplot as plt
res = [gauss(0,1) for i in range(100000)]
plt.hist(res,bins=1000)
#plt.show()
print("================collections標準庫=========")
#提供容器數據類型,可以看作之前學習過的組合數據類型的擴展
#namedtuple,具名元組,即有名字的元組
#構建一個新的元組子類,定義方法如下:typename是元組名字,field_names是域名, 即元組裏面要存的元素的名字
import collections
#collections.namedtuple(typename,field_names,*,rename=False,defaults=None,module=None)
Point = collections.namedtuple("Point",["x","y"])
#對Point對域名賦值,完成初始化操作
p = Point(1,y=2)
print(p)
#p作爲一個元組,具有元組的屬性,可以調用屬性,解包賦值
print(p.x)
print(p.y)
#有元組的性質
print(p[0])
print(p[1])
x,y = p
print(x)
print(y)
print(isinstance(p,tuple))
#Counter  計數器工具
from collections import Counter
s = "牛奶奶找劉奶奶買牛奶"
colors = ['red','blue','red','green','blue','blue']
cnt_str = Counter(s)
cnt_color = Counter(colors)
print(cnt_str)
print(cnt_color)
#Counter是字典類型的子類
print(isinstance(Counter(),dict))
#最常見的統計 -- most_commom(n) 提供n個頻率最高的元組和計數
#比如打印出cnt_color中2個出現頻率最高的元素和計數
print(cnt_color.most_common(2))
#將已經統計好的元素展開 -- elements()
print(list(cnt_str.elements()))
#其他一些加減操作
c = Counter(a=3,b=1)
d = Counter(a=1,b=2)
print(c+d)
#雙向隊列 可以方便的在隊列兩邊高效、快速的增加和刪除元素
from collections import deque
d = deque('cde')
print(d)
d.append("f") #右端增加
d.append("g")
d.appendleft("b")#左端增加
d.appendleft("g")
print(d)
d.pop()  #右端刪除
d.popleft()#左端刪除
print(d)

print("================itertools標準庫===========")
#itertools標準庫中有很多產生迭代器的方法
#排列組合迭代器
#product  -- 笛卡爾積
import itertools
for i in itertools.product('ABC','01'):
    print(i)
for i in itertools.product('ABC',repeat = 3):
    print (i)
#permutations  排列
for i in itertools.permutations('ABCD',3):  #從ABCD中取3個進行排列,3是排列的長度
    print(i)
for i in itertools.permutations(range(3)):
    print(i)

#combinations 組合
for i in itertools.combinations('ABCD',2): #2是組合的長度
    print(i)
for i in itertools.combinations(range(4),3):
    print(i)
#combinations_with_replacement -- 元素可重複組合
for i in itertools.combinations_with_replacement('ABC',2): #2是組合的長度
    print(i)
for i in itertools.product('ABC',repeat=2):
    print(i)

#拉鍊
#zip -- 短拉鍊
for i in zip("ABC","012","xyz"):
    print(i)
#長度不一致時,執行到最短的對象處,就停止
for i in zip("ABC","012345"):
    print(i)
#長度不一致時,執行到最長對象處,就停止,缺省的元素用None或指定字符替代
for i in itertools.zip_longest("ABC","012345"):
    print(i)
for i in itertools.zip_longest("ABC","012345",fillvalue="?"):
    print(i)
#無窮迭代器
#count(start=0,step=1) 計數
#創建一個迭代器 它從start值開始,返回均勻間隔的值
print(itertools.count(10))
#cycle  循環
#創建一個迭代器,返回iterable中所有元素,無限重複
print(itertools.cycle("ABC"))
#repeat(object[,times]) --重複
#其他迭代器
#chain(iterables)  鎖鏈 把一組迭代對象串聯起來 形成一個更大的迭代器
#enumerate(iterable,start=0) 枚舉 python內置
#groupby(iterable,key=None) 分組

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章