Python 推导式学习
list 列表推导式
[exp1 if condition else exp2 for x in y]
[exp for x in y if condition]
直接看例子
在0-9自然数中,偶数不变,奇数0
>>> test = [x if x%2==0 else 0 for x in range(10)]
>>> print(test)
[0, 0, 2, 0, 4, 0, 6, 0, 8, 0]
在0-9自然数中,偶数平方,奇数不变
>>> test = [x**2 if x%2==0 else x for x in range(10)]
>>> print(test)
[0, 1, 4, 3, 16, 5, 36, 7, 64, 9]
在0-9自然数中,只输出偶数平方
>>> test = [x**2 for x in range(10) if x%2==0]
>>> print(test)
[0, 4, 16, 36, 64]
在0-4自然数中,输出元祖(x,y) x为偶数,y为奇数
>>> test = [(x,y) for x in range(5) if x%2==0 for y in range(5) if y%2==1]
>>> print(test)
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
dict 字典推导式
{key:value for key,value in existing_data_structure}
枚举
>>> test = ['a','b','c','qq','e']
>>> dict = {k:v for k,v in enumerate(test)}
>>> print(dict)
{0: 'a', 1: 'b', 2: 'c', 3: 'qq', 4: 'e'}
把大写key变小,且给0
>>> test = {'a':'b','Q':'e','d':2}
>>> dict = {k.lower():test.get(k.lower(),0) for k in test.keys()}
>>> print(dict)
{'a': 'b', 'q': 0, 'd': 2}
set 集合推导式
{exp for item in seq if condition}
去重统一格式为首字母大写
>>> test = ['Bob','Joey','bob','joey']
>>> res = {n[0].upper()+n[1:].lower() for n in test}
>>> print(res)
{'Bob', 'Joey'}