目录
- 三元表达式(掌握)
- 列表推导式(掌握)
三元表达式(掌握)
条件成立时的返回值 if 条件 else 条件不成立时的返回值
x = 10
y = 20
print(f"x if x > y else y: {x if x > y else y}")
x if x > y else y: 20
列表推导式(掌握)
[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
类似于
res=[]
for item1 in iterable1:
if condition1:
for item2 in iterable2:
if condition2
...
for itemN in iterableN:
if conditionN:
res.append(expression)
print(F"[i for i in range(10)]: {[i for i in range(10)]}")
[i for i in range(10)]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(F"[i**2 for i in range(10)]: {[i**2 for i in range(10)]}")
[i**2 for i in range(10)]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
下面只是秀操作,不推荐使用,否则只有你自己看得懂了。
name_list = ['nick', 'sean', 'jason', 'tank']
print(
f"[name if name=='nick' else name+'sb' for name in name_list]: {[name if name=='nick' else name+'sb' for name in name_list]}")
[name if name=='nick' else name+'sb' for name in name_list]: ['nick', 'seansb', 'jasonsb', 'tanksb']
原文地址:https://www.cnblogs.com/nickchen121/p/10778650.html
时间: 2024-10-08 22:04:44