python - Python3的map函数中排除空值
问题描述
我map
用来处理 Python3.6 中的列表:
def calc(num):
if num > 5:
return None
return num * 2
r = map(lambda num: clac(num), range(1, 10))
print(list(r))
# => [2, 4, 6, 8, 10, None, None, None, None]
我期望的结果是:[2, 4, 6, 8, 10]
.
当然,我可以用它filter
来处理map
结果。但是有没有办法map
直接返回我想要的结果?
解决方案
map
不能直接过滤掉项目。它为每个输入项输出一项。您可以使用列表理解None
从结果中过滤掉。
r = [x for x in map(calc, range(1,10)) if x is not None]
(这只calc
对范围内的每个数字调用一次。)
旁白:没有必要写lambda num: calc(num)
. 如果你想要一个返回结果的函数calc
,只需使用calc
它自己。
推荐阅读
- c# - 如何在 Unity 中获取分配给游戏对象的所有材质
- javascript - Reactjs 无限滚动组件总是渲染新数据
- reactjs - 反应:TypeError:this.props.users.map 不是函数
- c# - 嗨,我正在尝试更改单元格值更改事件中 gridview 列的值,但每次发生时我都没有得到正确的输出
- java - 为什么即使计算正确,该方法仍返回 NaN?
- javascript - 用 axios 刮擦时身体丢失
- c++ - 主线程和线程池
- reactjs - useEffect redux 状态已更改,但未显示数据
- c# - 如何在 c# (Telegram bot) 中实现 register_next_step_handler?
- amazon-web-services - 活动项目的 DynamoDB TTL