【廖雪峰Python習題集】列表生成式
阿新 • • 發佈:2019-01-01
如果list中既包含字串,又包含整數,由於非字串型別沒有lower()方法,所以列表生成式會報錯:
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
使用內建的isinstance
函式可以判斷一個變數是不是字串:
>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False
請修改列表生成式,通過新增if
語句保證列表生成式能正確地執行:
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>>[s.lower() for s in L if isinstance(s,str)]
執行結果如下圖所示: