# 列表生成式和生成器

2018-02-27 11:28:47来源:oschina作者:pkookp8人点击

[]的内部是一个for循环，用来生成每一个元素

l = [x for x in range(2,10)]
print(l)
==============================
[2, 3, 4, 5, 6, 7, 8, 9]

for循环可以加if判断，例如可以生成2-9的偶数：

l = [x for x in range(2,10) if x % 2 == 0]
print(l)
==============================
[2, 4, 6, 8]

l = [x + y for x in range(2,10) for y in range(3, 6) if (x + y) % 2 == 0]
print(l)
==============================
[6, 6, 8, 8, 8, 10, 10, 10, 12, 12, 12, 14]

l=[]
for x in range(2, 10):
for y in range(3, 6):
if (x + y) % 2 == 0:
l.append(x + y)
print(l) 生成器

g = (x for x in range(1, 10) if x % 2 == 0)
print(g)
print("next==========")
print(next(g))
print("for============")
for each in g:
print(each)==============================
at 0x0270C090>
next==========
2
for============
4
6
8

g是一个列表生成式，可以通过for循环获取每个元素，也可以用next获取下一个元素，获取下一个后无法返回到上一个，直到获取完

g = (x for x in range(1, 10) if x % 2 == 0)
print(g)
print("next==========")
print(next(g))
print("for============")
for each in g:
print(each)
print("next==========")
print(next(g))==============================
D:/Users/ZXW000/PycharmProjects/untitled/venv1/Scripts/python.exe D:/Users/ZXW000/PycharmProjects/untitled/mygenerator.py
Traceback (most recent call last):
File "D:/Users/ZXW000/PycharmProjects/untitled/mygenerator.py", line 53, in
print(next(g))
StopIteration at 0x006BC090>
next==========
2
for============
4
6
8
next==========
Process finished with exit code 1

g = (x for x in range(1, 10) if x % 2 == 0)
print(g)
print("while==========")
while True:
try:
print(next(g))
except StopIteration:
print("g is over")
break==============================
at 0x0223C090>
while==========
2
4
6
8
g is over

def func1():
for i in range(0,5):
print(i)
def func2():
for i in range(0,5):
yield(i)print("func1==========")
func1()
print("func2==========")
g = func2()
while True:
try:
print(next(g))
except StopIteration:
print("g is over")
break==============================
func1==========
0
1
2
3
4
func2==========
0
1
2
3
4
g is over

func1每次调用都会打印0-4总共5个数，但外部变量无法获取到func1内部的每个i

func2则不一样，使用yield关键字后func2就是一个生成器，可以通过for或next获取每个值

func1中print不会阻止函数继续运行，会一直运行直到return为止

def func3():
i=0
while True:
yield i
i += 1