Discuss / Python / 列表生成器

列表生成器

Topic source

向阳

#1 Created at ... [Delete] [Delete and Lock User]

如果if 在for 后面,则为条件筛选,不符合条件的列表值被筛出,自动排除字符串以外的其他类型值。

L2 = [s.lower() for s in L1 if isinstance(s,str)]
L2 = ['hello', 'world', 'apple']

而如果想要保留数字的话,则可以选择使if 在for 前面,这样会对L1中每一个元素都进行运算。

L2 = [s.lower() if isinstance(s,str) else s for s in L1 ]
L2 = ['hello', 'world', 18, 'apple', None]

另:

if isinstance(s,str) # == 1

值本身为1,无须再加上是否为真的判断。


  • 1

Reply