简体   繁体   English

是否可以使用map将函数应用于参数列表并忽略结果?

[英]Is it ok to use map to apply function to arguments list and ignore the results?

Do you think that it is OK to use map for an applying function to arguments list and ignore the results? 你认为使用map作为参数列表的应用函数并忽略结果是可以的吗?

map(foo, bar)

It may appears as bug to person who is reading code. 它可能看起来像正在阅读代码的人的错误。

When you want the result using map is a perfectly fine way to apply a function to each item in a list, although many find it clearer to write it as a list comprehension or generator: 当你想要使用map的结果时,将函数应用于列表中的每个项目是一种非常好的方法,尽管许多人发现将它作为列表推导或生成器写得更清楚:

result = [foo(x) for x in bar]

However if you don't intend to use the result of the function call and are interested only in the side-effects then you should write using a procedural style instead: 但是,如果您不打算使用函数调用的结果并且只对副作用感兴趣,那么您应该使用过程样式来编写:

for x in bar:
    foo(x)

This behavior is frowned upon. 这种行为令人不悦。 Use a for loop unless you intend to make use of the returned list. 除非您打算使用返回的列表,否则请使用for循环。

Here's how I hack it together: 这是我一起破解它的方式:

from itertools import imap, ifilterfalse

tuple(ifilterfalse(None, imap(lambda x: x+1, range(10))))

That tuple will always be empty (given this input). tuple将始终为空(给定此输入)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM