列表推导式
[TOC[
一、列表推导式
[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 = ['allen', 'sean', 'jason', 'tank']
print(
f"[name if name=='allen' else name+'sb' for name in name_list]: {[name if name=='allen' else name+'sb' for name in name_list]}")
[name if name=='allen' else name+'sb' for name in name_list]: ['allen', 'seansb', 'jasonsb', 'tanksb']