python - 为什么将 list() 包裹在 map 周围会导致函数运行?

标签 python multithreading

我要解决的问题是在多线程庄园中映射函数列表。这些函数都打印出一些东西并有一个返回值。这些返回值中的每一个都将存储在一个列表中。这是代码...

 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() 调用包装 map ,那么确切的 map 功能确实不起作用。

 >>> 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 对象,它会记住需要做什么(就像生成器一样),但在您请求结果之前不会做任何工作(从 map 对象的结果创建一个列表就是要求它们全部一次)

map在Python2中已经返回一个列表,所以类似于Python3中的list(map(...))

通常不认为 Pythonic 仅仅因为它们的副作用而使用 map 或 list comprehension。如果您只是使用 for 循环,那么事情何时发生就不会产生歧义

for x in mythreads:
    x.start()

关于python - 为什么将 list() 包裹在 map 周围会导致函数运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34298751/

相关文章:

python - Argparse python,在帮助菜单中删除子解析器列表

python - Pylons 导入 Psycopg2 错误

python - GridSearchCV - 错误 : The truth value of an array with more than one element is ambiguous. 使用 a.any() 或 a.all()

python - 为什么 f.write 会覆盖 elif 语句后的一行?

python - 从 2 个数据帧计算加权股票 yield

java - 多线程java优化

python - 如何修复 'fatal Python error: _enter_buffered_busy: could not aquire lock for <_io.BufferedWriter name=' <stdout >'> at interpreter shutdown' 错误?

混淆 fork 和全局变量

java - 使用帖子的线程问题

java - 我应该为此动画使用 SwingWorker、线程或递归更新吗?