問題描述
在 python 2 中,我使用 map
將函數應用于多個項目,例如,刪除所有匹配模式的項目:
In python 2, I used map
to apply a function to several items, for instance, to remove all items matching a pattern:
map(os.remove,glob.glob("*.pyc"))
當然我忽略了os.remove
的返回碼,我只想刪除所有文件.它創建了一個列表的臨時實例,但它確實有效.
Of course I ignore the return code of os.remove
, I just want all files to be deleted. It created a temp instance of a list for nothing, but it worked.
在 Python 3 中,由于 map
返回的是迭代器而不是列表,因此上面的代碼什么也不做.我找到了一種解決方法,因為 os.remove
返回 None
,我使用 any
強制對完整列表進行迭代,而不創建 列表
(性能更好)
With Python 3, as map
returns an iterator and not a list, the above code does nothing.
I found a workaround, since os.remove
returns None
, I use any
to force iteration on the full list, without creating a list
(better performance)
any(map(os.remove,glob.glob("*.pyc")))
但這似乎有點危險,特別是在將其應用于返回某些內容的方法時.另一種使用單行而不創建不必要列表的方法?
But it seems a bit hazardous, specially when applying it to methods that return something. Another way to do that with a one-liner and not create an unnecessary list?
推薦答案
map()
(以及從 2.7 到 3.x 的許多其他函數)返回生成器而不是列表的變化是一種節省內存的技術.在大多數情況下,更正式地寫出循環不會降低性能(它甚至可能更適合于可讀性).
The change from map()
(and many other functions from 2.7 to 3.x) returning a generator instead of a list is a memory saving technique. For most cases, there is no performance penalty to writing out the loop more formally (it may even be preferred for readability).
我會提供一個例子,但@vaultah 在評論中指出:仍然是單線:
I would provide an example, but @vaultah nailed it in the comments: still a one-liner:
for x in glob.glob("*.pyc"): os.remove(x)
這篇關于在項目列表上調用一個函數的最簡潔方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!