首页 > 解决方案 > 如何在python中将字典键与全局变量绑定?

问题描述

import threading
from time import sleep


v1 = 100
dictionary = {'key':v1}

def fn1():
    global v1
    for i in range(30):
        sleep(0.2)
        v1 = i

def fn2():
    global dictionary # this line is totatlly unnecessary, I know 
    for i in range(30):
        sleep(0.2)
        print(dictionary['key'])

th1 = threading.Thread(target=fn1)
th1.start()
th2 = threading.Thread(target=fn2)
th2.start()

此代码仅输出 100,我希望它输出 1、2、3 ... 更改字典中的值并不是真正的解决方案 - 它需要在更复杂的情况下工作,但如有必要会重写

谢谢!

标签: pythonpython-3.xdictionary

解决方案


为了更深入地了解正在发生的事情:当您创建字典时 v1 指向 100 并且对值 100 的引用被复制到字典中dictionary = {'key':v1}

>>> d={'key':v1}
>>> id(v1)
140715103675136
>>> id(d['key'])
140715103675136

如您所见,v1 和 dict 都位于内存中的同一位置。

然后在循环中更改 v1 指向的引用,一旦完成,它将指向 Python 存储值 29 的位置。但是循环永远不会更新字典指向的引用。

如果要更改字典的值,可以使用可变类型,例如列表,然后弹出元素。

v1 = [100]
dictionary = {'key': v1}
def fn1():
  global v1
  for i in range(30):
    sleep(0.2)
    v1.append(i)
    #or: v1[0] = i

def fn2():
  global dictionary # this line is totatlly unnecessary, I know 
  for i in range(30):
    sleep(0.2)
    print(dictionary['key'].pop[0])
    #or:print(dictionary['key'][0])

推荐阅读