1. 程式人生 > >python的for...in...if...語句

python的for...in...if...語句

給定 pan 新的 list logs pre ... 說明 cnblogs

Python中,for...[if]...語句一種簡潔的構建List的方法,從for給定的List中選擇出滿足if條件的元素組成新的List,其中if是可以省略的。下面舉幾個簡單的例子進行說明。

>>> a=[12, 3, 4, 6, 7, 13, 21]
>>> newList = [x for x in a]
>>> newList
[12, 3, 4, 6, 7, 13, 21]
>>> newList2 = [x for x in a if x%2==0]
>>> newList2
[12, 4, 6]

python的for...in...if...語句