[英]Why does wrapping a list() around a map cause functions to run?
我要解決的問題是在多線程庄園中映射一系列功能。 這些函數都打印出一些內容並具有返回值。 這些返回值中的每一個都將存儲在列表中。 這是代碼...
import threading
import time
def PauseAndPrint1Seconds(num):
time.sleep(1)
print("Finished Pausing" + num)
return [1]
def PauseAndPrint2Seconds(num):
time.sleep(2)
print("Finished Pausing" + num)
return [2, 2]
def PauseAndPrint3Seconds(num):
time.sleep(3)
print("Finished Pausing" + num)
return [3, 3, 3]
def PauseAndPrint4Seconds(num):
time.sleep(4)
print("Finished Pausing" + num)
return [4, 4, 4, 4]
myfuncs = [PauseAndPrint1Seconds, PauseAndPrint2Seconds, PauseAndPrint3Seconds, PauseAndPrint4Seconds]
result = [None] * len(myfuncs)
def wrapFunc(i, num):
result[i] = myfuncs[i](num)
mythreads = [threading.Thread(target=wrapFunc, args = (i, " 12345")) for i in range(len(myfuncs))]
map(lambda x: x.start(), mythreads)
map(lambda x: x.join(), mythreads)
線程從未啟動,我回來了……
>>> map(lambda x: x.start(), mythreads)
<map object at 0x7fd1a551b3c8>
>>> result
[None, None, None, None]
如果我將map函數更改為簡單循環,則似乎可以正常工作
>>> for x in mythreads:
... x.start()
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
>>> result
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
同樣奇怪的是,如果我使用list()調用包裝地圖,則確實無法使用的確切地圖功能確實會起作用。
>>> list(map(lambda x: x.start(), mythreads))
[None, None, None, None]
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
Finished Pausing 12345
>>> result
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
總結一下……1.我是Python的新手,對不起,如果我錯過了一些基本的知識2.我知道有一種更簡便的方法。 這是我理解的問題。
這是Python2和Python3之間的區別。
Python3返回一個地圖對象,該對象記住需要完成的操作(如生成器),但是直到您索要結果之前才做任何工作(從地圖對象的結果中創建一個列表會立即要求所有這些操作)
map
在Python2已經返回一個列表,所以類似於list(map(...))
在Python3
通常,不僅僅將map或list理解用於副作用是不認為是Pythonic的。 如果您只是使用for
循環,那么什么時候發生就不會有歧義
for x in mythreads:
x.start()
映射函數返回生成器。 這意味着,當您嘗試獲取結果時,它將調用該函數,就像您這樣做: list(map(..))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.