线程内的print()输出错误的值

2024-10-01 11:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图重新创建一个愚蠢的想法,称为睡眠排序,但是输出远远超出预期

我期待着

0
1
2
3
5

不管我得到什么

0
5
5
5
5

…这是wierd,因为线程会:睡眠(项目)秒,然后打印该项目

这是我的密码

import threading
import time

def sleepSort(lst):
    for item in lst:
        threading.Thread(target = lambda: (
            time.sleep(item),
            print(item)
        )).start()

sleepSort([3, 0, 2, 1, 5])

我的代码有问题吗?提前非常感谢


Tags: 项目inimport密码fortime排序def
1条回答
网友
1楼 · 发布于 2024-10-01 11:39:20

这是许多语言的典型行为,是由“后期绑定”引起的。您应该显式地传递参数以避免这种情况,还应该使用类似于“python后期绑定”的谷歌搜索

def sleepSort(lst):
    for item in lst:
        threading.Thread(target = lambda item: (
            time.sleep(item),
            print(item)
        ), args=(item, )).start()

相关问题 更多 >