python - 如何在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 ... 更改字典中的值并不是真正的解决方案 - 它需要在更复杂的情况下工作,但如有必要会重写
谢谢!
解决方案
为了更深入地了解正在发生的事情:当您创建字典时 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])
推荐阅读
- javascript - RegEx 替代lookbehind
- angular - 在 Angular 中使用 HTTP 请求测试私有方法
- .htaccess - Opencart Redirect 301 最后带有“/”
- r - Lavaan 错误:要替换的项目数不是替换长度的倍数
- google-bigquery - Google Cloud Stackdriver 日志记录 - 将日志导出到 BigQuery - 拒绝访问数据集
- caching - BigQuery 中的查询缓存
- jupyter-notebook - Jupyter:单击散点图中的点时触发输出,该点替换以前的输出(而不是被附加)
- c# - 在开关中访问返回的字符串数组时出现问题
- django - 使用 Django 的 ORM 进行复杂的 M2M 过滤
- node.js - ReactJS:使用 Bearer 授权获取 GET 方法