2024-10-04 15:22:35 发布
网友
我试着这样做:
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])
你只是创建了一个元组,没有使用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]
你只是创建了一个元组,没有使用lambda
像这样修改代码
更好地使用列表理解
为什么不简单地使用:
相关问题 更多 >
编程相关推荐