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.列表解析与生成器表达式都是一种便利的编程方式,只不过生成器表达式更节省内存

 3.字典推导式

# 将一个字典的key和value对调
dir = {"A":2,"B":3}
dir1 = {dir[i]:i for i in dir.keys()}
print(dir1)
# 合并大小写对应的value值,将k统一成小写
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
mcase1 = {i.lower():mcase.get(i.lower(), 0) + mcase.get(i.upper(), 0) for i in  mcase}
print(mcase1)

 

posted on 2019-06-16 11:38  wzc27229  阅读(137)  评论(0编辑  收藏  举报