Discuss / Python / 想了下,理解题意的话是将字符串变为小写,那么不是字符串的是不是就应该保持不变呢

想了下,理解题意的话是将字符串变为小写,那么不是字符串的是不是就应该保持不变呢

Topic source
#_*_ coding:utf-8 _*_
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[s.lower() for s in L1 if isinstance(s,str)]
L2

[40]:

['hello', 'world', 'apple']

[43]:

L2=[s.lower() if isinstance(s,str) else s for s in L1]
L2

[43]:

['hello', 'world', 18, 'apple', None]

王sir不要

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

L2 = [s.lower() for s in L1 if isinstance(s,str) else s]

这个为什么不行呢

pino52667

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

同问

上面文章写了,在一个列表生成式中,for前面的if ... else是表达式,而for后面的if是过滤条件,不能带else


  • 1

Reply