python推导式
一、列表推导式
例一:30以内所有能被3整除的数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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]
例二:30以内所有能被3整除的数的平方
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print(multiples)
例三:找到嵌套列表中名字含有两个‘e’的所有名字
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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]) # 注意遍历顺序,这是实现的关键
二、字典推导式
例一:将一个字典的key和value对调
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
例二:合并大小写对应的value值,将k统一成小写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()} print(mcase_frequency)
三、集合推导式
例:计算列表中每个值的平方,自带去重功能
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
squared = {x**2 for x in [1, -1, 2]} print(squared) # Output: set([1, 4])
练习题:
例1: 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
l = ['namHe','ss','seFtfcSd','d','EThdyYhy'] print( [i.upper() for i in l if len(i) >=3])
例2: 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
t1 = [(x,y) for x in range(6) if x % 2 is 0 for y in range(6) if y % 2 is 1] print(t1)
例3: 求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
M = [[1,2,3],[4,5,6],[7,8,9]] m = [[x,y,z] for x in M[0] if x == 3 for y in M[0] if y == 6 for z in M[0] if z == 9] print(m)