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) ]
filter
map
将丢弃索引并保留原始数字
在此示例中留下 [0, 4]
关于Python 映射 lambda 过滤器帮助使用 IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960889/