列表生成式

有使用循環生成列表太麻煩,可以用列表生成式,只用一行語句生成列表。[x*x for x in range(4)]>>>[0, 1, 4, 9]

 

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']










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