1.如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:
L = [‘Hello’, ‘World’, 18, ‘Apple’, None]
[s.lower() for s in L]
Traceback (most recent call last):
File “”, line 1, in
File “”, line 1, in
AttributeError: ‘int’ object has no attribute ‘lower’
使用内建的isinstance函数可以判断一个变量是不是字符串:
L1 = ['Hello', 18, 'World', 'Apple', ]
a = [i.lower() for i in L1 if isinstance(i,str)]
print(a)