Python学习_推导式
# 列表推导式
# 格式
[表达式 for 变量 in 旧列表]
[表达式 for 变量 in 旧列表 if 条件]
names = ['tom','lily','abs','jack','steven','jenny','danny']
result = [name.capitalize() for name in names if len(name)>3]
print(result)
>> ['Lily', 'Jack', 'Steven', 'Jenny', 'Danny']
- 元组、字典也有类似用法
# 嵌套的用法
list1 = [(x, y) for x in range(4) if x % 2 == 0 for y in range(4) if y % 2 != 0]
print(list1)
>> [(0, 1), (0, 3), (2, 1), (2, 3)]
# 字典推导式
dict1 = {'name':'Tom','salary':4000}
dict2 = {'name':'Lucy','salary':5000}
dict3 = {'name':'Jack','salary':4500}
dict4 = {'name':'Lily','salary':7000}
list1 = [dict1, dict2, dict3, dict4]
newlist = [employee['salary']+200 if employee['salary']>5000 else employee['salary']+500 for employee in list1]
print(newlist)
>> [4500, 5500, 5000, 7200]
# 集合推导式
# 格式
{表达式 for 变量 in 旧列表}
{表达式 for 变量 in 旧列表 if 条件}
- 与列表推导式一致,多了一个去重的功能
# 字典推导式
dict1 = {'a':'A','b':'B','c':'C','d':'C'}
newdict = {value:key for key, value in dict1.items()}
print(newdict)
>> {'A': 'a', 'B': 'b', 'C': 'd'}
编辑 (opens new window)
上次更新: 2023/08/09, 13:21:24