python从random生成列表_Python 学习DAY 17 列表生成式,生成器,迭代器,time模块,random模块...
********************************************列表生成式******************
a=[x for x in range(10)]? ? ?[0,1,2,3,4,5,6,7,8,9]
a=[x*2 for x in range(10)]?? [0,2,4,6,8,10.....]? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? a=[x*x for x in range(10)]? ? ? ?平方
def f(n):
return n**3
a=[f(x) for x in range(10)]? ? ? ? 也可以放函數
t=('123',8)
a,b=t? ? ? a='123' b=8? ? 賦值取元組元素
********************************************生成器***************************
a=(x*2 for x in range(10))? 小括號,生成器對象? (生成器創建方式1)
next(a)==a.__next__()? 拿到第一個數0,內部方法,不在明面上用
next(a)=2
next(a)=4? ?只能按順序一個一個拿
生成器在創建的時候已經決定了能計算出值的個數,調用next的次數超過這個值就會報stopiteration
生成器就是一個可迭代對象 iterablre,可以用for循環遍歷
for循環內部做了三件事:
1.調用對象的iter()方法,返回一個迭代器對象
2.啟用一個while循環
i=next(list_iterator)
生成器兩種創建方式:
1.()方式
2.yield關鍵字方式
def foo()? ? ? ? ? ??(生成器創建方式2)
print('ok')
yield 1
print('ok2')
yield 2
g=foo()
next(g)? ?從頭執行到yield 1,并返回1給next(g)
next(g)? ?從頭執行到yield 2,并返回2給next(g)
for i in foo():
print i
輸出結果 ok 1 OK2 2
for i in 可迭代對象,什么是可迭代對象,內部有iter方法的都是可迭代對象
b.send(None) == next(b)? 第一次send前如果沒有next,只能傳一個send(None)
def bar():
print('ok')
count=yield 1
print(count)
yield 2
b=bar
next(b)
b.send('eeee')? ? 給count賦值eeee,將2返回至b.send('eeee')
*****************************************迭代器****************************************
生成器都是迭代器,迭代器不一定是生成器
l=【1,2,3,4】,元組,字典
d=iter(l)? ? 返回一個迭代器對象
next(d)=1
什么是迭代器?滿足兩個條件:(迭代器協議)
1.有iter方法
2.有next方法
1.調用可迭代對象的iter方法,返回一個迭代器對象
2.調用迭代器的next方法
3.處理stopiteration異常
isinstance 判斷對象是否是正確的類型
isinstance (l,iterable)ture? ?可迭代對象
isinstance (l,iterator)FAlse 迭代器
***************************************time模塊***********************************
impot time
time.time()? 拿到時間戳*****
time.clock() 計算CPU執行的時間
time.sleep() *****
time.gmtime() 英國結構化時間,utc時間
time.localtime() 本地時間******
time.strftime((%Y--%m--%d %H:%M:%S),(time.localtime)) 字符串時間******
time.strptime('2019-10-9','%Y-%m-%d) 字符串時間轉換成結構化時間 ,單取一個年,可能用到********
表示時間的方式:時間戳、結構化時間,字符串格式化時間
time.ctime(時間戳,默認為空),時間戳轉化固定格式字符串時間
time.mktime(結構化時間),結構化時間轉化時間戳
*************************datetime模塊************************************
import datetime
datetime.datetime.now()? ? 友好的字符串時間表示
datetime.date.time.
*******************************random模塊*******************************
import random
random.random()? ?創建一個(0,1)的隨機數
random.randint(1,8) 創建一個1,8的整數,包括8
random.choice('hello') 在序列里隨機選一個數
random.sample(【['1,2,3',4,【1,2】】,2)隨機選兩個
random.randrange(1,10),1~9選一個數,不包括10
chr(65)=A? ASCII碼轉換
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python从random生成列表_Python 学习DAY 17 列表生成式,生成器,迭代器,time模块,random模块...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用VC写Assembly代码(5) --
- 下一篇: 遍历ArrayList易犯错误