1.什么是生成式
生成式就是生成器的一种特殊写法
2.写法
- a.
生成器 = (表达式 for 变量 in 序列) --> 让变量去序列中取值,每取一个值就将对应的表达式的值作为生成器的元素
def 函数名():
for 变量 in 序列:
yield 表达式
- b.
生成器 = (表达式 for 变量 in 序列 if 条件语句)
def 函数名():
for 变量 in 序列:
if 条件语句:
yield 表达式
gen1 = (x*2 for x in 'abc123')
print(gen1)
print(next(gen1))
print(next(gen1))
print(next(gen1))
# 这个是生成式(x*2 for x in 'abc123')展开成生成器的写法
def func1():
for x in 'abc123':
yield x*2
gen2 = ((value, key) for key, value in {'name': 'xiaoming', 'age': 10}.items())
print(next(gen2)) # ('xiaoming', 'name')
print(next(gen2)) # (10, 'age')
def func2():
for key, value in {'name': 'xiaoming', 'age': 10}.items():
yield (value, key)
gen3 = (x for x in range(10) if x&1)
print(next(gen3)) # 1
print(next(gen3)) # 3
print(next(gen3)) # 5
def func3():
for x in range(10):
if x & 1:
yield x
3.将迭代器和生成器转换成其他序列
list1 = list(gen3)
print(list1) # [7, 9]
# print(next(gen3)) # StopIteration
gen5 = (x.upper() for x in '12as67sj2is8' if 'a'<=x<='z')
# list2 = list(gen5)
# # print(list2)
def yt_list(seq):
new = []
for x in seq:
new.append(x)
return new
list2 = yt_list(gen5)
print(list2)
# print(next(gen5)) # StopIteration
# [生成式] -> 直接将生成式对应的生成器转换成列表
list3 = [x.upper() for x in '12as67sj2is8' if 'a' <= x <= 'z']
print(list3)
# 练习: 交换字典的key和value的位置
dict1 = {'a': 1, 'b': 2, 'c': 3}
result = dict((x, y) for y, x in dict1.items())
print(result)
网友评论