如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错.使用内建的isinstance函数可以判断一个变量是不是字符串:
>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:(当时写的)
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = []
for x in L1:
if isinstance(x,str) == True:
L2.append(x)
[s.lower() for s in L2]
后来发现只需一行即可:
L2 = [s.lower() for s in L1 if isinstance(s,str)]