列表推导式

一、列表推导式

[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']
posted @ 2019-11-14 21:14  つつつつつつ  阅读(147)  评论(0编辑  收藏  举报