告诉某人“我想为iterable
中的每个元素应用func
的副作用”的首选方式是什么。python map中的副作用(python“do”block)
# 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;标准库中是否有一个功能已经相当于?
你应该使用选项1.它是最好的沟通你的代码是必要的,并不会构造无用的结果列表。 – millimoose
'地图'和列表的理解是等价的。 'walk_for_side_effects'电话没用。使用选项1. –
@PavelAnossov:不在python 3中; 'map()'返回一个迭代器。 –