简体   繁体   English

如何在python中将字典键与全局变量绑定?

[英]How to bond dictionary key with global variable in 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()

This code outputs only 100's, I would want it to output 1, 2, 3 ... Changing value in dictionary is not really a solution - it needs to work in a quite more complex situation, but will rewrite if necessary这段代码只输出 100 个,我希望它输出 1, 2, 3 ... 改变字典中的值并不是真正的解决方案 - 它需要在更复杂的情况下工作,但如有必要会重写

Thanks!谢谢!

To provide a little more insight as to what is happening: When you create the dictionary v1 points to 100 and the reference to the value 100 is copied to the dictionary dictionary = {'key':v1}为了更深入地了解正在发生的事情:当您创建字典 v1 指向 100 并且对值 100 的引用被复制到字典dictionary = {'key':v1}

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

As you can see both v1 and the dict point at the same location in the memory.如您所见, v1 和 dict 都指向内存中的同一位置。

In the loop you then change the reference where v1 points to and once it is finished it will point to where Python stores the value 29. However the loop never updates the reference where your dictionary points to.然后在循环中更改 v1 指向的引用,一旦完成,它将指向 Python 存储值 29 的位置。但是,循环永远不会更新字典指向的引用。

If you want to change the value of the dictionary you could use a mutable type, such as a list and then pop the elements.如果要更改字典的值,可以使用可变类型,例如列表,然后弹出元素。

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])

One option you have is to have some indirection:您拥有的一种选择是有一些间接性:

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

def fn1():
    global v1
    for i in range(30):
        sleep(0.2)
        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'][0])

This uses a list to hold the integer as the first item.这使用一个列表来保存整数作为第一项。

Now the dict holds a reference to a list which is the same list all the time.现在 dict 持有对一个列表的引用,该列表一直是同一个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM