「普通道路」絕對是最好的方法,雖然itertools
沒有提供消耗不管出於什麼原因,你可能需要它配方:
import collections
from itertools import islice
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
這可以用於像:
consume(imap(func, my_list), None) # On python 3 use map
該函數執行速度最快,因爲它通過使用在C端運行的函數來避免python for循環開銷。
你的問題是 - 我怎樣才能執行某個列表中的每個元素的函數?使用'map()'有什麼問題? –
@BurhanKhalid它在內存中建立一個列表(很可能是一個'None'的列表)。 – jamylak
'for'循環(或類似的列表理解)對我來說似乎很簡潔。有時候,儘可能縮短事情比一個好習慣更容易陷入困境。簡潔性對於可讀性來說是有利的,但僅限於一點。自然語言有很多冗餘的原因。 – Steve314