來(lái)自于廖雪峰的Python3教程課后練習(xí) 如果list中既包含字符串,又包含整數(shù),由于非字符串類型沒(méi)有l(wèi)ower()方法,所以列表生成式會(huì)報(bào)錯(cuò):
>>> L = ['Hello', 'World', 18, 'Apple', None]>>> [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'使用內(nèi)建的isinstance函數(shù)可以判斷一個(gè)變量是不是字符串:
>>> x = 'abc'>>> y = 123>>> isinstance(x, str)True>>> isinstance(y, str)False請(qǐng)修改列表生成式,通過(guò)添加if語(yǔ)句保證列表生成式能正確地執(zhí)行:
# -*- coding: utf-8 -*-L1 = ['Hello', 'World', 18, 'Apple', None]L2 = [x.lower() for x in L1 if isinstance(x, str)]# 期待輸出: ['hello', 'world', 'apple']PRint(L2)新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注