简体   繁体   中英

Python map lambda filter help using IF

Given a list of N numbers, use a single list comprehension to produce a new list that only contains those values that are:

(a) even numbers, and
(b) from elements in the original list that had even indices

I am looking for a solution to the above problem. As suggested here there is an easy way to solve it but I would like to know if there is a way I can use a combination of map, lambda and filter on the "FULL" input list.

I am trying to do something like this but it doesn't work.

>>> map(lambda i,x : x%2==0 or (i+1)%2==0, range(0,len(l)-1),l)
[False, True, False, True, True]

Ideally I need to write something like (added "x if") but that doesnt work. Any suggestions?

map(lambda i,x : ***x if*** x%2==0 or (i+1)%2==0, range(0,len(l)-1),l)

The problem specifically says "use a single list comprehension".

That having been said, you could do something like this:

>>> map(lambda x: x[1], filter(lambda x: x[0] % 2 == 0 and x[1] % 2 == 0, enumerate([0, 1, 5, 4, 4])))

enumerate will zip the indices with the digits themselves producing [(0, 0), (1, 1), (2, 5), (3, 4), (4, 4)]

filter with the given lambda will only be satisfied if both numbers in the tuple are even

map with the given lambda will discard the indices and keep the original numbers

leaving you with [0, 4] for this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM