1.循环对象,主要调用next()
2.迭代器iterator(),在理解上可以和循环对象理解为一个东西。
3.生成器(generator)自定义的循环对象。
4.表推导(list comprehension)是快速生成表的方法。表推导用中括号。
L = [x**2 for x in range(10)]
练习:
>>> f=open("test.txt","w")
>>> f.writelines("1234\n abcd\n efg")
>>> f.close()
>>> x=open("test.txt","r")
>>> contents=x.read()
>>> print(contents)
1234
abcd
efg
>>> x.close()
>>> f=open("test.txt")
>>> f.next()
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
f.next()
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
>>> for line in open ("test.txt"):
print()
>>> print(line)
efg
>>> for line in open ("test.txt"):
print(line)
1234
abcd
efg
>>> def gen():
a=100
yield(a)
a=a*8
yield(a)
yield(1000)
>>> for i in gen():
print(i)
100
800
1000
>>> def gen():
for i in range(4):
yield(i)
>>> print(i)
1000
>>> def gen():
for i in range(4):
yield(i)
print(i)
>>>
>>> for i in gen():
print(i)
0
0
1
1
2
2
3
3
>>> L=[x**2 for x in range(10)]
>>> print(L)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> X1=[1,3,5]
>>> Y2=[9,12,13]
>>> L=[x**2 for (x,y)in zip(X1,Y2) if y>10]
>>> print(L)
[9, 25]
运行环境win7,python3.7.4