简体   繁体   English

Python映射Lambda过滤器使用IF的帮助

[英]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: 给定一个由N个数字组成的列表,请使用单个列表推导生成一个仅包含以下值的新列表:

(a) even numbers, and (a)偶数,以及
(b) from elements in the original list that had even indices (b)来自原始列表中具有偶数索引的元素

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. 如此处建议的那样有一种简单的方法可以解决该问题,但是我想知道是否有一种方法可以在“ FULL”输入列表中使用map,lambda和filter的组合。

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. 理想情况下,我需要写一些类似的东西(添加“ x if”),但这不起作用。 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)] enumerate将使用数字本身压缩索引,从而产生[(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 仅当元组中的两个数字均为偶数时,才会满足给定lambda的filter

map with the given lambda will discard the indices and keep the original numbers 具有给定lambda的map将丢弃索引并保留原始数字

leaving you with [0, 4] for this example 在此示例中,将[0,4]留给您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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