我需要在代码中更改什么才能得到这样的输出[None,2,None,4,None]

2024-10-04 15:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着这样做:

evenList = ((lambda x : x if x%2==0 else None), [1,2,3,4,5,6])

预期产量:

[None,2,None,4,None,6]

我得到:

(<function __main__.<lambda>>, [1,2,3,4,5,6])

Tags: lambdanoneifmainfunctionelse产量evenlist
2条回答

你只是创建了一个元组,没有使用lambda

像这样修改代码

In [10]: list(map((lambda x : x if x%2==0 else None), [1,2,3,4,5,6]))                                                                                                                                       
Out[10]: [None, 2, None, 4, None, 6]

更好地使用列表理解

In [11]: [i if i%2==0 else None for i in [1,2,3,4,5,6]]                                                                                                                                                      
Out[11]: [None, 2, None, 4, None, 6]

为什么不简单地使用:

>>> [x if x%2==0 else None for x in range(1,7)]
[None, 2, None, 4, None, 6]

相关问题 更多 >

    热门问题