python的for...in...if...语句
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]