-
展開嵌套序列
yield from運用
yield from iterable本質上等于for item in iterable
示例:把多層嵌套的序列展開成一個單層列表
>>> from collections import Iterable
#>>>yield from flatten(i)相當于for x in flatten(i):yield x
>>> def flatten(iterms,ignore_types=(str,bytes)):
for i in iterms:
if isinstance(i,Iterable) and not isinstance(i,ignore_types):
yield from flatten(i)
else:
yield i
>>> items = [1, 2, [3, 4, [5, 6], 7], 8]
>>> for x in flatten(items):
print(x)
1
2
3
4
5
6
7
8
>>> items1 = ['Dave', 'Paula', ['Thomas', 'Lewis']]
>>> for x in flatten(items1):
print(x)
Dave
Paula
Thomas
Lewis
>>>
-
合并后的排序迭代對象
一系列排序序列,將它們合并后得到一個排序序列并在上面迭代遍歷
運用heapq模塊merge()
函數,輸入序列必須是排過序的,且它不會預先讀取所有數據到堆棧中或者預先排序,也不會對輸入做任何的排序檢測。
它的工作原理:僅僅檢查所有序列的開始部分并返回最小的那個,這個過程一直會持續直到所有
輸入序列中的元素都被遍歷完。
>>> import heapq
>>> a=[1, 4, 7, 10]
>>> b=[2, 5, 6, 11]
>>> for c in heapq.merge(a,b):
print(c)
1
2
4
5
6
7
10
11
反過來驗證,輸入必須是排過序的,如果不是呢?
>>> a=[2,1,3]
>>> b=[2, 5, 6, 11]
>>> for c in heapq.merge(a,b):
print(c)
2
1
2
3
5
6
11
>>>
-
迭代器代替 while 無限循環
內置函數iter()
的運用,返回指定對象的迭代器- iter(iterable) 參數為可迭代對象
- iter(callable, sentinel) 持續調用參數callable直至其返回sentinel
f = open('1.txt')
for chunk in iter(lambda: f.read(10), ''):
print(chunk)
print("\n")