在一個列表生成式中,for前面的if ... else是表達式,而for後面的if是過濾條件,不能帶else。
L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [x.lower() for x in L1 if(isinstance(x,str)==True) ] # 測試: #print(L2) if L2 == ['hello', 'world', 'apple']: print('測試通過!') else: print('測試失敗!')
L3 = [x.lower() if(isinstance(x,str)==True) else x for x in L1] #['hello', 'world',18, 'apple',none]
#使用內建的isinstance
函數可以判斷一個變量是不是字符串
>>>a = 2
>>> isinstance (a,int)
True