python map中的副作用(python“do"块) [英] Side-effects in python map (python "do" block)
问题描述
告诉某人我想将 func
应用到 iterable
中的每个元素以消除其副作用的首选方式是什么."
What is the preferred way to tell someone "I want to apply func
to each element in iterable
for its side-effects."
# Option 1... clear, but two lines.
for element in iterable:
func(element)
# Option 2... even more lines, but could be clearer.
def walk_for_side_effects(iterable):
for element in iterable:
pass
walk_for_side_effects(map(func, iterable)) # Assuming Python3's map.
# Option 3... builds up a list, but this how I see everyone doing it.
[func(element) for element in iterable]
我喜欢选项 2;标准库中是否有已经等价的函数?
I'm liking Option 2; is there a function in the standard library that is already the equivalent?
推荐答案
避免变得聪明的诱惑.使用选项 1,它的意图是明确和不含糊的;您正在将函数 func()
应用于可迭代对象中的每个元素.
Avoid the temptation to be clever. Use option 1, it's intent is clear and unambiguous; you are applying the function func()
to each and every element in the iterable.
选项 2 只是让每个人都感到困惑,寻找 walk_for_side_effects
应该做什么(这确实让我感到困惑,直到我意识到您需要在 Python 3 中迭代 map()
).
Option 2 just confuses everyone, looking for what walk_for_side_effects
is supposed to do (it certainly puzzled me until I realized you needed to iterate over map()
in Python 3).
选项 3 应该在您实际从 func()
获得结果时使用,从不 用于副作用.只是为了副作用而抨击任何人这样做.列表推导式应该用于生成列表,而不是做其他事情.相反,您更难理解和维护您的代码(并且为所有返回值构建列表的启动速度较慢).
Option 3 should be used when you actually get results from func()
, never for the side effects. Smack anyone doing that just for the side-effects. List comprehensions should be used to generate a list, not to do something else. You are instead making it harder to comprehend and maintain your code (and building a list for all the return values is slower to boot).
这篇关于python map中的副作用(python“do"块)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!