I guess it comes down to a simple choice: get busy living or get busy dying.
1二汛、切片
倒數(shù)第一個(gè)元素的索引是-1
取后10個(gè)數(shù):L[-10:]
2、迭代
- dict: for value in d.values(), for k, v in d.items()
- from collections import Iterable
isinstance('abc', Iterable) # str是否可迭代 - for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
3耀态、列表生成式
list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][m + n for m in 'ABC' for n in 'XYZ']
import os # 導(dǎo)入os模塊
[d for d in os.listdir('.')] # os.listdir可以列出文件和目錄success: [x for x in range(1, 11) if x % 2 == 0]
error: [x for x in range(1, 11) if x % 2 == 0 else 0]success: [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
error: [x if x % 2 == 0 for x in range(1, 11)]
4、生成器
一邊循環(huán)一邊計(jì)算的機(jī)制暂雹,稱為生成器:generator首装, generator保存的是算法, 可迭代
g = (x * x for x in range(10))
next(g)g = (x * x for x in range(10))
for n in g:
print(n)
函數(shù)是順序執(zhí)行杭跪,遇到return語句或者最后一行函數(shù)語句就返回仙逻。而變成generator的函數(shù)驰吓,在每次調(diào)用next()的時(shí)候執(zhí)行,遇到y(tǒng)ield語句返回系奉,再次執(zhí)行時(shí)從上次返回的yield語句處繼續(xù)執(zhí)行
>>> def fib(max):
... n, a, b = 0, 0, 1
... while n < max:
... yield b
... a, b = b, a + b
... n = n + 1
... return 'done'
>>> f = fib(6)
>>> for n in fib(6):
... print(n)
但是用for循環(huán)調(diào)用generator時(shí)檬贰,發(fā)現(xiàn)拿不到generator的return語句的返回值。如果想要拿到返回值喜最,必須捕獲StopIteration錯(cuò)誤偎蘸,返回值包含在StopIteration的value中
>>> g = fib(6)
>>> while True:
... try:
... x = next(g)
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
5、迭代器
凡是可作用于for循環(huán)的對(duì)象都是可迭代對(duì)象瞬内,包括list迷雪,set等集合和生成器;
凡是可作用于next()函數(shù)的對(duì)象都是迭代器虫蝶,它們表示一個(gè)惰性計(jì)算的序列章咧,生成器都是迭代器;
集合數(shù)據(jù)類型如list能真、dict赁严、str等是可迭代對(duì)象但不是迭代器,不過可以通過iter()函數(shù)獲得一個(gè)迭代器對(duì)象粉铐。
例如:
if __name__ == "__main__":
a = [1, 2, 3]
b = iter(a)
try:
while True:
print(next(b))
except StopIteration as e:
print(e.value)
>>> output:
1
2
3
None
擴(kuò)展:
Python的Iterator對(duì)象表示的是一個(gè)數(shù)據(jù)流疼约,Iterator對(duì)象可以被next()函數(shù)調(diào)用并不斷返回下一個(gè)數(shù)據(jù),直到?jīng)]有數(shù)據(jù)時(shí)拋出StopIteration錯(cuò)誤蝙泼〕贪可以把這個(gè)數(shù)據(jù)流看做是一個(gè)有序序列,但我們卻不能提前知道序列的長度汤踏,只能不斷通過next()函數(shù)實(shí)現(xiàn)按需計(jì)算下一個(gè)數(shù)據(jù)织鲸,所以Iterator的計(jì)算是惰性的,只有在需要返回下一個(gè)數(shù)據(jù)時(shí)它才會(huì)計(jì)算溪胶。
Iterator甚至可以表示一個(gè)無限大的數(shù)據(jù)流搂擦,例如全體自然數(shù)。而使用list是永遠(yuǎn)不可能存儲(chǔ)全體自然數(shù)的哗脖。這就是list瀑踢,dict等集合跟生成器的本質(zhì)區(qū)別
參考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640