列表生成式

在一個列表生成式中,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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章