# Python——迭代器和解析(1)

2224人阅读 评论(0)

>>> for x in [1,2,3,4]:print(x**2,end=" ")

1 4 9 16 
>>> for x in (1,2,3,4):print(x**3,end = ' ')

1 8 27 64 
>>> for x in 'spam' :print(x*2,end=' ')

ss pp aa mm 

'可迭代对象'在语言设计中很普遍，基本上，这就是序列观念的通用化：如果对象是实际保存的序列，或者可以在迭代工具环境中一次产生一个结果的对象，就看做时可迭代的。
===============================================================================

>>> f = open(r'F:\002calc.py')
'temp = input("Please input a number:\\n")\n'
'num = int(temp)\n'
'if 1<=num<=100:\n'
'    print("your sister is beautiful!")\n'
'else:\n'
'    print("your oldfather is ugly!")\n'
''
''

>>> f = open(r'F:\002calc.py')
>>> f.__next__()
'temp = input("Please input a number:\\n")\n'
>>> f.__next__()
'num = int(temp)\n'
>>> f.__next__()
'if 1<=num<=100:\n'
>>> f.__next__()
'    print("your sister is beautiful!")\n'
>>> f.__next__()
'else:\n'
>>> f.__next__()
'    print("your oldfather is ugly!")\n'
>>> f.__next__()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
f.__next__()
StopIteration

>>> for line in open(r'F:\002calc.py'):
print(line.upper(),end='')

TEMP = INPUT("PLEASE INPUT A NUMBER:\N")
NUM = INT(TEMP)
IF 1<=NUM<=100:
PRINT("YOUR SISTER IS BEAUTIFUL!")
ELSE:
PRINT("YOUR OLDFATHER IS UGLY!")

>>> open(r'F:\002calc.py').readlines()
['temp = input("Please input a number:\\n")\n', 'num = int(temp)\n', 'if

1<=num<=100:\n', '    print("your sister is beautiful!")\n', 'else:\n', '

print("your oldfather is ugly!")\n'] 
>>> for line in open(r'F:\002calc.py').readlines():
print(line.upper(),end='')

TEMP = INPUT("PLEASE INPUT A NUMBER:\N")
NUM = INT(TEMP)
IF 1<=NUM<=100:
PRINT("YOUR SISTER IS BEAUTIFUL!")
ELSE:
PRINT("YOUR OLDFATHER IS UGLY!")

===============================================================================

>>> f = open(r'F:\002calc.py')
>>> next(f)
'temp = input("Please input a number:\\n")\n'
>>> next(f)
'num = int(temp)\n'

>>> L = [1,2,3]
>>> I = iter(L)
>>> I.next()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
I.next()
AttributeError: 'list_iterator' object has no attribute 'next'
>>> next(I)
1
>>> next(I)
2
>>> next(I)
3
>>> next(I)
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
next(I)
StopIteration

>>> f = open(r'F:\002calc.py')
>>> iter(f) is f
True
>>> f.__next__()
'temp = input("Please input a number:\\n")\n'
>>> next(f)
'num = int(temp)\n'

>>> L = [1,2,3]
>>> iter(L) is L
False
>>> L.__next__()
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
L.__next__()
AttributeError: 'list' object has no attribute '__next__'

>>> I = iter(L)
>>> I.__next__()
1
>>> next(I)
2

>>> L = [1,2,3]
>>> for x in L:
print(x**2,end=' ')

1 4 9 
>>> L
[1, 2, 3]
>>> I = iter(L)
>>> while True:
try:
x = next(I)
except StopIteration:
break
print(x**2,end=' ')

1 4 9 
===============================================================================

>>> D = {'a':1,'b':2,'c':3}
>>> for key in D.keys():
print(key,D[key])

b 2
a 1
c 3
>>> I = iter(D)
>>> next(I)
'b'
>>> next(I)
'a'
>>> next(I)
'c'
>>> next(I)
Traceback (most recent call last):
File "<pyshell#73>", line 1, in <module>
next(I)
StopIteration

>>> for key in D:
print(key,D[key])

b 2
a 1
c 3

>>> R = range(5)
>>> R
range(0, 5)
>>> I = iter(R)
>>> next(I)
0
>>> next(I)
1
>>> next(I)
2

>>> list(range(5))
[0, 1, 2, 3, 4]

>>> E = enumerate('spam')
>>> E
<enumerate object at 0x007C1AF8>
>>> I = iter(E)
>>> next(I)
(0, 's')
>>> next(I)
(1, 'p')
>>> next(I)
(2, 'a')
>>> next(I)
(3, 'm')
>>> list(enumerate('spam'))
[(0, 's'), (1, 'p'), (2, 'a'), (3, 'm')]

===============================================================================

>>> L = [1,2,3,4,5]
>>> for i in list(range(len(L))):
L[i] += 10

>>> L
[11, 12, 13, 14, 15]

>>> L = [1,2,3,4,5]
>>> L = [x+10 for x in L]
>>> L
[11, 12, 13, 14, 15]

---------------------------------------------------------------------------------------------------------------------------------------------

===============================================================================

>>> f = open(r'F:\002practice.py')
>>> lines = f.readlines()
>>> lines
['#print("Please input your name:")\n', 'name = input("Please input your name:\\n");\n', 'print("Hello "+name)\n']

>>> lines = [line.rstrip() for line in lines]
>>> lines
['#print("Please input your name:")', 'name = input("Please input your name:\\n");', 'print("Hello "+name)']

>>> lines = [line.rstrip() for line in open(r'F:\002practice.py')]
>>> lines
\n");', 'print("Hello "+name)']

---------------------------------------------------------------------------------------------------------------------------------------------

>>> lines = [line.rstrip() for line in open(r'F:\002practice.py') if line[0] == 'p']
>>> lines
['print("Hello "+name)']

>>> [x+y for x in 'abc' for y in '123']
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']
>>> [x+y for (x,y) in zip('abc','123')]
['a1', 'b2', 'c3']

【注意：应用于列表解析的嵌套循环，它和zip是不一样的，看上例↑】

===============================================================================

>>> uppers = [line.upper() for line in open(r'F:\002practice.py')]
>>> uppers
['#PRINT("PLEASE INPUT YOUR NAME:")\n', 'NAME = INPUT("PLEASE INPUT YOUR NAME:\\N");\n', 'PRINT("HELLO "+NAME)\n']
>>> map(str.upper,open(r'F:\002practice.py'))
<map object at 0x007C65B0>
>>> list(map(str.upper,open(r'F:\002practice.py')))
['#PRINT("PLEASE INPUT YOUR NAME:")\n', 'NAME = INPUT("PLEASE INPUT YOUR NAME:\\N");\n', 'PRINT("HELLO "+NAME)\n']
>>> 'y = 2 \n' in open(r'F:\002practice.py')
False

Python中还包含了各种处理迭代的其他内置函数：sorted排序可迭代对象中的各项，zip组合可迭代对象中的各项，enumerate根据相对位置来配对可迭代对象中的项filter选择一个函数为真的项，reduce针对可迭代对象中成对的项运行一个函数。所有的这些都接受一个可迭代的对象，并且在Python3.0中，zip、enumerate和filter也像map一样返回一个可迭代对象（全部显示需要用list）：

>>> sorted(open(r'F:\002practice.py'))
['#print("Please input your name:")\n', 'name = input("Please input your name:\\n");\n', 'print("Hello "+name)\n']
>>> list(zip(open(r'F:\002practice.py'),open(r'F:\002practice.py')))
[('#print("Please input your name:")\n', '#print("Please input your name:")\n'), ('name = input("Please input your name:\\n");\n', 'name = input("Please input your name:\\n");\n'), ('print("Hello "+name)\n', 'print("Hello "+name)\n')]
>>> list(enumerate(open(r'F:\002practice.py')))
[(0, '#print("Please input your name:")\n'), (1, 'name = input("Please input your name:\\n");\n'), (2, 'print("Hello "+name)\n')]
sorted是应用了迭代协议的一个内置函数，它就像是最初的列表的sort方法，但是它返回一个新的排序的列表作为结果并且可以在任何可迭代对象上运行
【注意：和map以及其他函数不同，sorted在Python3.0中返回一个真正的列表而不是一个可迭代对象】

max和min分别返货一个可迭代对象中的最大和最小的项。

>>> sum([1,2,3,4])
10
>>> any(['spam','','ni'])
True
>>> all(['spam','','ni'])
False
>>> max([1,2,3,4])
4
>>> min({1,2,3,4})
1
【注意：all要求所有为真才返回真，any是如果有一项为真则返回真】

>>> list(open(r'F:\002practice.py'))
['#print("Please input your name:")\n', 'name = input("Please input your name:\\n");\n', 'print("Hello "+name)\n']
>>> tuple(open(r'F:\002practice.py'))
('#print("Please input your name:")\n', 'name = input("Please input your name:\\n");\n', 'print("Hello "+name)\n')
>>> '&&'.join(open(r'F:\002practice.py'))
'#print("Please input your name:")\n&&name = input("Please input your name:\\n");\n&&print("Hello "+name)\n'
>>> a,b,c = open(r'F:\002practice.py')
>>> a,c
('#print("Please input your name:")\n', 'print("Hello "+name)\n')
>>> a,*b = open(r'F:\002practice.py')
>>> a,b
('#print("Please input your name:")\n', ['name = input("Please input your name:\\n");\n', 'print("Hello "+name)\n'])

>>> set(open(r'F:\002practice.py'))
{'name = input("Please input your name:\\n");\n', '#print("Please input your name:")\n', 'print("Hello "+name)\n'}
>>> {line for line in open(r'F:\002practice.py')}
{'name = input("Please input your name:\\n");\n', '#print("Please input your name:")\n', 'print("Hello "+name)\n'}
>>> {i:line for i,line in enumerate(open(r'F:\002practice.py'))}
{0: '#print("Please input your name:")\n', 1: 'name = input("Please input your name:\\n");\n', 2: 'print("Hello "+name)\n'}

>>> {key:value for (key,value) in zip([1,2,3],['a','b','c'])}
{1: 'a', 2: 'b', 3: 'c'}

>>> {line for line in open(r'F:\002practice.py') if line[0]=='p'}
{'print("Hello "+name)\n'}
>>> {i:line for i,line in enumerate(open(r'F:\002practice.py'))if line[0]=='p'}
{2: 'print("Hello "+name)\n'}

>>> def f(a,b,c):print(a,b,c,sep='&')

>>> f(1,2,3)
1&2&3
>>> f(*[1,2,3])
1&2&3
>>> f(*open(r'F:\002practice.py'))
&print("Hello "+name)

>>> filter(bool,['spam','','ni'])
<filter object at 0x037AE2B0>
>>> list(filter(bool,['spam','','ni']))
['spam', 'ni']
===============================================================================

range支持len和索引，它不是自己的迭代器（手动迭代时，要使用iter产生一个迭代器），并且，它支持在结果上的多个迭代器，这些迭代器会记住它们各自的位置

>>> R = range(3)
>>> next(R)

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
next(R)
TypeError: list object is not an iterator

>>> I1 = iter(R)
>>> next(I1)
0
>>> next(I1)
1
>>> I2 = iter(R)
>>> next(I2)
0
>>> next(I2)
1

>> Z = zip((1,2,3),(10,11,12))
>>> Z1 = iter(Z)
>>> Z2 = iter(Z)
>>> next(Z1)
(1, 10)
>>> next(Z1)
(2, 11)
>>> next(Z2)
(3, 12)

>>> M = map(abs,(-2,0,1))
>>> M1 = iter(M)
>>> M2 = iter(M)
>>> next(M1)
2
>>> next(M1)
0
>>> next(M2)
1

===============================================================================

>>> D = dict(a=1,b=2,c=3)
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> K = D.keys()
>>> K
dict_keys(['b', 'c', 'a'])
>>> next(K)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next(K)
TypeError: 'dict_keys' object is not an iterator
>>> I = iter(K)
>>> next(I)
'b'
>>> next(I)
'c'
>>> for k in D.keys():
print(k,end=' ')

b c a 

>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> K = D.keys()
>>> list(K)
['b', 'c', 'a']
>>> V = D.values()
>>> list(V)
[2, 3, 1]
>>> V
dict_values([2, 3, 1])
>>> list(D.items())
[('b', 2), ('c', 3), ('a', 1)]
>>> for (k,v) in D.items():
print(k,v,end=' ')

b 2 c 3 a 1

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> for key in D:
print(key)

a
c
b

>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> for k in sorted(D.keys()):
print(k,D[k],end=' ')

a 1 b 2 c 3
>>> D
{'b': 2, 'c': 3, 'a': 1}
>>> for k in sorted(D):
print(k,D[k],end=' ')

a 1 b 2 c 3 
===============================================================================

1.使用yield语句，用户定义的函数可以转换为可迭代的生成器函数
2.当编写在圆括号的时候，列表解析转变为可迭代的生成器表达式
3.用户定义的类通过__iter__或__getitem__运算符重载变得可迭代。

===============================================================================

1：for循环和迭代器之间有什么关系？

for循环会使用迭代协议来遍历迭代的对象中的每一个项。for循环在开始时会通过它传给iter内置函数，以便从可迭代对象中获得一个迭代器，返回对象中有需要的next方法。for循环会在每次迭代中调用该对象的__next__方法（由next内置函数运行），而且会捕捉StopIteration异常，从而决定何时停止循环。支持这种模式的任何对象，都可以用于for循环以及其他迭代环境中。

2.for循环和列表解析直接有什么关系？

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：340812次
• 积分：5336
• 等级：
• 排名：第5085名
• 原创：152篇
• 转载：39篇
• 译文：5篇
• 评论：46条
Contact me
GitHub
博客专栏
 JavaWeb框架 文章：6篇 阅读：13869
 XML 文章：7篇 阅读：26354
 Servlet 文章：24篇 阅读：61595
 Python3 文章：44篇 阅读：77030
最新评论