在常用的所有编程语言中,for和while等关键字,都可以帮助我们完成循环重复的任务。但是在Python中,提供了迭代协议与解析工具,能使得迭代更高效,语法更简洁。尽管不是必须的,但是这些工具很有用并且强大,是高级Python程序员常用的技巧。
为了在总结文件迭代器时更形象,笔者还是在计算机D盘下新建一个文本文档命名为test.txt,内容初始化如下所示:
aaaaaa
bbbbbb
cccccc
dddddd
eeeeee
ffffff
gggggg
f = open('D:/test.txt')
f.__next__() # 'aaaaaa\n'
f.__next__() # 'bbbbbb\n'
f.__next__() # 'cccccc\n'
f.__next__() # 'dddddd\n'
f.__next__() # 'eeeeee\n'
f.__next__() # 'ffffff\n'
f.__next__() # 'gggggg'
f.__next__() # StopIteration
for line in open('D:/test.txt'):
line = line.rstrip()
print(line)
for line in open('D:/test.txt').readlines():
line = line.rstrip()
print(line)
'''输出如下
aaaaaa
bbbbbb
cccccc
dddddd
eeeeee
ffffff
gggggg
'''
f = open('D:/test.txt')
next(f) # 'aaaaaa\n'
next(f) # 'bbbbbb\n'
next(f) # 'cccccc\n'
next(f) # 'dddddd\n'
next(f) # 'eeeeee\n'
next(f) # 'ffffff\n'
next(f) # 'gggggg'
next(f) # StopIteration
L = [1, 2, 3]
I = iter(L)
type(I) #
I.__next__() # 1
next(I) # 2
L = [1, 2, 3]
L = [x +10 for x in L] # [11, 12, 13]
f = open('D:/test.txt')
lines = f.readlines() # ['aaaaaa\n', 'bbbbbb\n', 'cccccc\n', 'dddddd\n', 'eeeeee\n', 'ffffff\n', 'gggggg']
lines = [line.rstrip() for line in lines] # ['aaaaaa', 'bbbbbb', 'cccccc', 'dddddd', 'eeeeee', 'ffffff', 'gggggg']
上述列表解析可以结合文件迭代进行内存优化,不用提前打开文件。对于较大的文件,列表解析的优势更加显著。
lines = [line.rstrip() for line in open('D:/test.txt')] # ['aaaaaa', 'bbbbbb', 'cccccc', 'dddddd', 'eeeeee', 'ffffff', 'gggggg']
[x + y for x in 'abc' for y in 'lmn'] # ['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']
[x **2 for x in range(10) if x % 2 ==0] # [0, 4, 16, 36, 64]
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
N = [[2, 2, 2], [3, 3, 3], [4, 4, 4]]
[M[row][col] * N[row][col] for row in range(3) for col in range(3)] # [2, 4, 6, 12, 15, 18, 28, 32, 36]
[[M[row][col] * N[row][col] for row in range(3)] for col in range(3)] # [[2, 12, 28], [4, 15, 32], [6, 18, 36]]
def gen(N):
for i in range(N):
yield i ** 2
def main():
for i in gen(5):
print(i)
if __name__ == '__main__':
main()
'''
输出
0
1
4
9
16
'''
def gen(N):
for i in range(N):
yield i ** 2
def main():
x = gen(5)
print(type(x)) #
print(x.__next__()) # 0
print(x.__next__()) # 1
print(x.__next__()) # 4
print(x.__next__()) # 9
print(x.__next__()) # 16
print(x.__next__()) # StopIteration
if __name__ == '__main__':
main()
def gen(N):
for i in range(N):
yield i ** 2
def main():
for i in gen(5):
print(i)
if __name__ == '__main__':
main()
'''
输出
0
'''
def gen(N):
for i in range(N):
x = yield i ** 2
print(x)
def main():
G = gen(5)
next(G)
r = G.send(77)
print(r)
r = G.send(88)
print(r)
r = next(G)
print(r)
if __name__ == '__main__':
main()
'''
输出
77
1
88
4
None
9
'''
def gen(N):
for i in range(N):
x = yield i ** 2
print(x)
# 下面是没有初始化生成器的错误情况
def main():
G = gen(5)
# next(G)
r = G.send(77)
print(r)
r = G.send(88)
print(r)
r = next(G)
print(r)
if __name__ == '__main__':
main()
'''
输出
TypeError: can't send non-None value to a just-started generator
'''
def gen(N):
for i in range(N):
yield i ** 2
def main():
X = gen(5)
I1, I2 = iter(X), iter(X)
print(I1.__next__()) # 0
print(I2.__next__()) # 1
print(I1.__next__()) # 4
print(I2.__next__()) # 9
print(I1.__next__()) # 16
print(I2.__next__()) # StopIteration
if __name__ == '__main__':
main()
R = range(3)
I1 = iter(R)
I2 = iter(R)
next(I1) # 0
next(I2) # 0
L = [1, 2, 3]
I1 = iter(L)
I2 = iter(L)
next(I1) # 1
next(I2) # 1
Z = zip((1, 2, 3), (10, 11, 12))
I1 = iter(Z)
I2 = iter(Z)
next(I1) # (1,10)
next(I2) # (2,11)
L = [3, 2, 1]
I = iter(L)
sorted(I) # [1, 2, 3]
sorted(L) # [1, 2, 3]
L1 = [1, 2, 3]
L2 = [4, 5, 6]
I1 = iter(L1)
I2 = iter(L2)
zip(I1, I2) #
list(zip(I1, I2)) # [(1, 4), (2, 5), (3, 6)]
zip(L1, L2) #
list(zip(L1, L2)) # [(1, 4), (2, 5), (3, 6)]
L = [1, 2, 3]
I = iter(L)
enumerate(I) #
list(enumerate(I)) # [(0, 1), (1, 2), (2, 3)]
enumerate(L) #
list(enumerate(L)) # [(0, 1), (1, 2), (2, 3)]
L = [-3, -2, -1, 0, 1, 2, 3]
I = iter(L)
filter(bool, I) #
list(filter(bool, I)) # [-3, -2, -1, 1, 2, 3]
filter(bool, L) #
list(filter(bool, L)) # [-3, -2, -1, 1, 2, 3]
reduce(lambda x, y: x + y, (1, 2, 3, 4)) # 10
reduce(lambda x, y: x + y, (1, 2, 3, 4), 100) # 110
L = [1, 2, 3]
I = iter(L)
sum(I) # 6
sum(L) # 6
L = [0, 1, 2, 3]
I = iter(L)
any(I) # True
any(L) # True
all(I) # True
all(L) # False
L = [0, 1, 2, 3]
I = iter(L)
max(I) # ValueError: max() arg is an empty sequence
max(L) # 3
min(I) # ValueError: min() arg is an empty sequence
min(L) # 0
以上,欢迎各位读者朋友提出意见或建议。
欢迎阅读笔者后续博客,各位读者朋友的支持与鼓励是我最大的动力!
written by jiong
我从来不想独身,
却有预感晚婚。
我在等,
世上唯一契合灵魂。