可以与三目运算符搭配使用
dict1 = {'name': "by", "age": 20}
dict2 = {'name': "ss", "age": 25}
dict3 = {'name': "sa", "age": 24}
dict4 = {'name': "xs", "age": 27}
list1 = [dict1, dict2, dict3, dict4]
list2 = [{'name': elm['name'], 'age': elm['age'] + 20 if elm['age'] > 23 else elm['age'] + 2} for elm in list1]
print(list2)
超出范围会报错
# 列表推导式
list1 = [x * 3 for x in range(10)]
print(type(list1), list1)
# 列表生成式
list2 = (x * 3 for x in range(10))
print(type(list2), list2)
print(list2.__next__())
print(list2.__next__())
print(list2.__next__())
print(next(list2))
print(next(list2))
print(next(list2))
yield:返回该值、暂停该线程,通过next()唤醒,下一步可以y = yield x
send:发送一个值给刚才暂停的yield线程,赋值给y
def gen():
i = 0
while i < 5:
temp = yield i
print('temp', temp)
i += 1
return '没有更多的数据'
g = gen()
print(g)
print(g.send('a'))
print(g.__next__())
print(g.__next__())
print(g.__next__())