开发者

Adding even values to new list Python

If I have a list and I want to creat开发者_开发问答e a list with only even values of the original list, how would I do that?

I originally have:

list1 = [1,2,3,4,5]
list2 = []
for v in list1:
    if v % 2 == 0:
        list2 += v
print list2


List comprehension is the way to go:

list1 = [1,2,3,4,5]
list2 = [i for i in list1 if i%2 == 0]
print list2 # => [2, 4]


If you want to extend an existing list2 (not necessarily initially empty):

list2.extend(v for v in list1 if v % 2 == 0)

If there's no "initial value" for list2, and you just want to build it from scratch:

list2 = [v for v in list1 if v % 2 == 0]

You'll notice that the inner part is identical -- you can use that part in different ways (inside brackets to create a new list, as argument to .extend to extend an existing list, and so forth).


You can use list comprehensions:

list2 = [x for x in list1 if x % 2 == 0]


list2 = [x for x in list1 if x%2 == 0]


list2 = [i for i in list1 if not i%2]


I find this to be the most readable solution:

list2 = filter(lambda x: x % 2 == 0: list1)

or if you have to use this function multiple times:

is_even = lambda x: x % 2 == 0

list2 = filter(is_even, list1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜