先列出问题,有一个列表如下
L1 = ['Hello', 'World', 18, 'Apple', None]
我们想得到结果
['hello', 'world', 'apple']
这时候我们可以使用列表生成式
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
print(L2)
列表生成式的部分可以抽象概况为
[根据x计算的函数或表达式 for x in 迭代器 (可选)if …]
这里的可选if语句,是对原迭代器(在上面的例子中是列表