各种推导式玩法
推导式套路
之前我们已经学习过最简单的列表推导和生成器表达式。但是除此之外,其实还有字典推导式、集合推导式等等
下面就是一个列表推导式为例的推导式详细格式,同样适用于其他推导式
variable = [out_exp_res for out_exp in input_list if out_exp == 2]
out_exp_res: #列表生成式,可以是有返回值的函数
for out_exp input_list: #迭代inp_list 将 out_exp_res 表达式中
if out_exp == 2 #根据条件过滤那些值可以
列表推导式
例一:30以内所有内被3整除的数
multioless = [i for i in range(30) if i%3 is 0]
print(multioless)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
例二:30以内所有能被3整除的数的平方
def squard(x):
return x*x
multiples = [squard(i) for i in range(30) if i%3 is 0]
print(multiples)
[0, 9, 36, 81, 144, 225, 324, 441, 576, 729]
例三:找到嵌套列表中名字含有两个‘e’的所有名字
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
multiples =[named for name in names for named in name if named.count('e') is 2]
print(multiples)
['Jefferson', 'Wesley', 'Steven', 'Jennifer']
字典推导式
例一:将一个字典的key和value对调
macase = {'a':10,'b':34}
macas_frequency = {macase[k] : k for k in macase}
print(macas_frequency)
{10: 'a', 34: 'b'}
例二:合并大小写对应的value值,将k统一成小写
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)
{'a': 17, 'b': 34, 'z': 3}
集合推导式
例:计算列表中每个值的平方,自带去重功能
squared = {x**2 for x in [1, -1, 2]}
print(squared)
# Output: set([1, 4])
{1, 4}
练习题:
例1: 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
str_list = ['sdAfD','asOPa','sd','a','tg','AsasS','Av','qwerAtyuifAghjk']
str_list = [str.upper() for str in str_list if len(str) >= 3]
print(str_list)
['SDAFD', 'ASOPA', 'ASASS', 'QWERATYUIFAGHJK']
例2: 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
tupl_list = [(x, y) for x in range(0,6,2) for y in range(1,6,2)]
print(tupl_list)
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
例3: 求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
M = [[1,2,3],[4,5,6],[7,8,9]]
m = [ml[2] for ml in M ]
print(m)
[3, 6, 9]