for後面還可加上if語句,
>>>L = ['Hello', 'World', 18, 'Apple', None]
>>> a = [i for i in L if isinstance(i,str)]
>>> a
['Hello', 'World', 'Apple']
isinstance()是python內建函數,可以判斷一個變量的類型。
>>> isinstance('hello',str)
True
>>> isinstance(123,str)
False
>>> isinstance(123,int)
True
>>>d = {'name':'lee','gender':'male','age':21}
>>> isinstance(d,dict)
True
列表生成式可以同時使用兩種變量甚至更多:
>>> d = {'gender': 'male', 'name': 'lee'}
>>> [k + '=' + v for k,v in d.items()]
['gender=male', 'name=lee']
還可以使用兩種循環,生成全排列。
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']