告訴某人「我想爲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()'返回一個迭代器。 –