Python 映射 lambda 过滤器帮助使用 IF

标签 python dictionary lambda reduce

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

我正在寻找上述问题的解决方案。按照建议here有一种简单的方法可以解决这个问题,但我想知道是否有一种方法可以在“完整”输入列表上使用映射、lambda 和过滤器的组合。

我正在尝试做这样的事情,但它不起作用。

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

理想情况下,我需要编写类似(添加“x if”)的内容,但这不起作用。有什么建议吗?

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

最佳答案

问题特别指出“使用单个列表理解”。

话虽如此,你可以这样做:

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

enumerate 将使用数字本身压缩索引,生成 [(0, 0), (1, 1), (2, 5), (3, 4), (4, 4) ]

仅当元组中的两个数字均为偶数时,才会满足具有给定 lambda 的

filter

带有给定 lambda 的

map 将丢弃索引并保留原始数字

在此示例中留下 [0, 4]

关于Python 映射 lambda 过滤器帮助使用 IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960889/

相关文章:

python - pygame.init() 什么时候会返回 (6,0) 以外的东西?

c# - Lambda 表达式、捕获的变量和线程

c# - 带有 null 的字符串如何给出除 null 之外的其他结果

java - 如何在 Scala 中使用 Java lambda

python - 如何从 pandas DataFrame 中删除列?

python - 无法访问 PyUSB 后端

python - 未绑定(bind)本地错误 : local variable 'arith_flex' referenced before assignment

json - 取一个 JSON 字符串,将其解码为 map[string]interface{},编辑并将其编码为 []byte 似乎比它应该更复杂

python - 在Python中使用嵌套for循环加载字典

swift - 功能和选项练习