┌──[root@vms81.liruilongs.github.io]-[~] └─$python3 Python 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license"for more information. >>>
>>> deffrange(start, stop, increment): ... x = start ... while x < stop: ... yield x ... x += increment ... >>> for n in frange(0, 4, 0.5): ... print(n) ... 0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 >>>
>>> f = open('/etc/passwd') >>> for line inreversed(list(f)): ... print(line,end='') ... opensips:x:997:993:OpenSIPS SIP Server:/var/run/opensips:/sbin/nologin oprofile:x:16:16:Special user account to be used by OProfile:/var/lib/oprofile:/sbin/nologin nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin ......
# Forward iterator def__iter__(self): n = self.start while n > 0: yield n n -= 1 # Reverse iterator def__reversed__(self): n = 1 while n <= self.start: yield n n += 1
print(format('逆序','*>20')) for rr inreversed(Countdown(5)): print(rr) print(format('正序','*>20')) for rr in Countdown(5): print(rr)
def__iter__(self): for lineno, line inenumerate(self.lines, 1): self.history.append((lineno, line)) yield line
defclear(self): self.history.clear()
if __name__ == "__main__": withopen('/etc/services') as f: lines = linehistory(f) for line in lines: if'8080'in line: for lineno, hline in lines.history: print('{}:{}'.format(lineno, hline), end='')
>>> items = ['a','b','c'] >>> from itertools import permutations >>> for p in permutations(items): ... print(p) ... ('a', 'b', 'c') ('a', 'c', 'b') ('b', 'a', 'c') ('b', 'c', 'a') ('c', 'a', 'b') ('c', 'b', 'a') >>>
如果你想得到指定长度的所有排列,你可以传递一个可选的长度参数。
1 2 3 4 5 6 7 8 9 10
>>> for p in permutations(items,2): ... print(p) ... ('a', 'b') ('a', 'c') ('b', 'a') ('b', 'c') ('c', 'a') ('c', 'b') >>>
使用itertools.combinations()可得到输入集合中元素的所有的组合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
>>> from itertools import combinations >>> for i in combinations(items,3): ... print(i) ... ('a', 'b', 'c') >>> for i in combinations(items,2): ... print(i) ... ('a', 'b') ('a', 'c') ('b', 'c') >>> for i in combinations(items,1): ... print(i) ... ('a',) ('b',) ('c',) >>>
这里需要注意的一点,combinations必须要指定参与组合的元素个数
1 2 3 4 5 6
>>> for i in combinations(items): ... print(i) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Required argument 'r' (pos 2) not found
以索引-值对的形式迭代序列
迭代一个序列的同时跟踪正在被处理的元素索引。
内置的 enumerate() 函数可以很好的解决这个问题:
1 2 3 4 5 6 7 8
>>> my_list = ['a', 'b', 'c'] >>> for idx,item inenumerate(my_list): ... print(idx,item) ... 0 a 1 b 2 c >>>
可以指定索引
1 2 3 4 5 6 7
>>> for idx,item inenumerate(my_list,1): ... print(idx,item) ... 1 a 2 b 3 c >>>
在处理列表嵌套的元组的时候需要注意的问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> data = [ (1, 2), (3, 4), (5, 6), (7, 8) ] >>> for n, (x, y) inenumerate(data): ... print(n,x,y) ... 012 134 256 378 >>> for n, x, y inenumerate(data): ... print(n,x,y) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: not enough values to unpack (expected 3, got 2) >>>
>>> from itertools import chain >>> a = [1, 2, 3, 4] >>> b = ['x', 'y', 'z'] >>> for x in chain(a, b): ... print(x) ... 1 2 3 4 x y z >>>
其他的容器也可以
1 2 3 4 5 6
# Various working sets of items active_items = set() inactive_items = set() # Iterate over all items for item in chain(active_items, inactive_items): # Process item
defflatten(items, ignore_types=(str, bytes)): for x in items: ifisinstance(x, Iterable) andnotisinstance(x, ignore_types): yieldfrom flatten(x) else: yield x
items = [1, 2, [3, 4, [5, 6], 7], 8] # Produces 1 2 3 4 5 6 7 8 for x in flatten(items): print(x)
items = ['Dave', 'Paula', ['Thomas', 'Lewis']] for x in flatten(items): print(x)
简单的梳理一下这个方法,利用递归和yield from 的语法,深度遍历所以的元素,返回的遍历的每个元素,需要说明isinstance(x, Iterable)用于判断某个元素是否可迭代。
>>> import heapq >>> withopen('16943_26281_10022_20220523_DATA.txt','rt') as file1,\ ... open('16943_26281_10022_20220523_DATA.txt','rt') as file2,\ ... open('16943_26281_10022_20220523_DATA_2022.txt','wt') as file3: ... for c in heapq.merge(file1,file2): ... file3.write(c) ...