标签:nbsp 表达 names alice 条件 生成器 range and ext
1.列表推导式
li = [ 6*i for i in range(10)] print(li) ----------------------------------------- [0, 6, 12, 18, 24, 30, 36, 42, 48, 54]
-----------------------------------------
str = ["输出%s" %i for i in range(10)]
print(str)
-----------------------------------------
[‘输出9‘, ‘输出5‘, ‘输出1‘, ‘输出0‘, ‘输出4‘, ‘输出8‘, ‘输出2‘, ‘输出6‘, ‘输出7‘, ‘输出3‘]
----------------------------------------
#添加if条件
multiples = [i for i in range(30) if i % 3 is 0] print(multiples) # Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
------------------------------------------------------
#找到嵌套列表中名字含有两个‘e’的所有名字
names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘], [‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]] print([name for lst in names for name in lst if name.count(‘e‘) >= 2]) # 注意遍历顺序,这是实现的关键
2.生成器表达式
li = ( 2*i for i in range(10)) print(li) print(next(li)) # #next本质就是调用__next__ print(li.__next__()) print(next(li))
----------------------------------------
2
4
6
----------------------------------------
for i in li:
print(i)
总结:
1.把列表解析的[]换成()得到的就是生成器表达式
2.列表解析与生成器表达式都是一种便利的编程方式,只不过生成器表达式更节省内存
标签:nbsp 表达 names alice 条件 生成器 range and ext
原文地址:https://www.cnblogs.com/wzc27229/p/11031028.html