第十四章 迭代器和解析、第一部分

#1.
#A:文件迭代器
#B:__next__()每次调用返回下一个对象,到达序列尾部时候会引发StopIteration异常
#C:内置函数next()会自动调用对象的__next__()方法
'''
文件1.txt内容:
123
abc
szn
'''
pFile = open("1.txt")
bValue0 = iter(pFile) is pFile  #bValue0 = True
str0 = pFile.__next__()         #str0 = '123
'
str1 = next(pFile)              #str1 = 'abc
'
str2 = pFile.__next__()         #str2 = 'szn'
try:
    str3 = pFile.__next__()
except StopIteration:
    pass                        #执行至此
pFile.close()

#2.
#A:文件对象就是自己的迭代器,而列表以及其他很多内置对象,其不是自身的迭代器,因为他们支持多次打开迭代器,对这样的对象,必须调用iter来启动迭代
#B:对于字典的迭代器,在迭代环境下回自动返回一个键,直接的效果是不需要再调用keys方法来遍历字典键
#C:列表解析比功能相同的手动的for循环的速度快,因为列表解析的迭代在解释器内部是以C语言的速度执行的,而不是以手动python代码执行的
L0 = [1, 2, 3]
bValue0 = iter(L0) is L0        #bValue0 = False
#L0.__next__()                  #运行出错
it = iter(L0)
L1 = list(it)                   #L1 = [1, 2, 3]

it = iter(L0)
value = it.__next__()           #value = 1
value = it.__next__()           #value = 2
L2 = list(it)                   #L1 = [3]

L1 = [2, 3, 4]
L2 = [x ** 2 for x in L1 if x % 2 == 0] #L2 = [4, 16]
L3 = [x + y for x in L1 for y in L2]    #L3 = [6, 18, 7, 19, 8, 20]

#3.
#A:sum(), any(), all(), max(), min()
L1 = [0, 1, 2]
value0 = sum(L1)                #value0 = 3
value1 = sum(iter(L1))          #value1 = 3
value2 = any(L1)                #value2 = True
value3 = all(L1)                #value3 = False
vlaue4 = all(L1[1:])            #vlaue4 = True
value5 = max(L1)                #value5 = 2
value6 = min(L1)                #value6 = 0

#4.
#A:tuple 元组
#B:join()将一个子字符串放置于一个可迭代对象中包含的字符之间
T1 = tuple(L1)                  #T1 = (0, 1, 2)
L1 = ['1', 'a', 'b']
s0 = '&&'.join(L1)              #s0 = '1&&a&&b'
s1 = '*'.join("str")            #s1 = 's*t*r'

#5.
#A:函数调用中用到一种特殊的*arg形式,它会把一个集合的值解包为单个的参数
def fun(a, b, c) : print(str(a), str(b), str(c), sep = '&')
L0 = [1, 2, 3]
fun(*L0)                        #输出1&2&3
fun(*iter(L0))                  #输出1&2&3
#fun(L0)                        #运行错误
#fun(iter(L0))                  #运行错误

L0 = [1, 2]
L1 = ['a', 'b']
R1, R2 = zip(*zip(L0, L1))      #R1 = (1, 2) R2 = ('a', 'b')

#6.
#A:filter对于传入的函数返回true的可迭代对象中的每一项,它都会返回该项
'''
filter	英[ˈfɪltə(r)]
美[ˈfɪltɚ]
n.	滤波器
'''
L0 = [1, 2, 3, 4]
def Fun(a) : return a % 2 == 0
L0 = list(filter(Fun, L0))      #L0 = [2, 4]

#7.
#A:range它不是自己的迭代器,支持在其结果上的多个迭代器,这些迭代器会记住他们各自的位置
#B:zip,filter不支持相同结果上的多个迭代器
R = range(1, 10)
b0 = iter(R) == R               #b0 = False
b1 = iter(R) is iter(R)         #b1 = False

L0 = [0, 1, 2]
f0 = filter(bool, L0)
b1 = iter(f0) is iter(f0)       #b1 = True

L0 = [1]; L1 = [2]
z0 = zip(L0, L1)
b1 = iter(z0) is iter(z0)       #b1 = True

#8.
#A:
'''
python的迭代协议:有__next__方法的对象会前进到下一个结果,而在一系列结果的末尾则会引发StopIteration。
在python中,任何的可迭代对象都能以for循环或者其他迭代工具遍历,因为所有迭代工具内部工作都是每次迭代调用__next__,并且捕捉StopIterator异常来确定何时离开
'''

  

原文地址:https://www.cnblogs.com/szn409/p/6637837.html