python字典:指定空白字典

2024-06-07 22:21:38 发布

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

为什么以下代码会出现以下错误,以及如何将其分配给函数中的空白字典:

import time 

dictionary_power_readings = {}

def update_dict():
    ApparentPower = "power"
    dictionary_power_readings[time.time()] = ApparentPower
    print(dictionary_power_readings)
    dictionary_power_readings ={} 




while True:
    update_dict()
    time.sleep(1)

Traceback (most recent call last): File "updating_dict_from_function.py", line 15, in update_dict() File "updating_dict_from_function.py", line 7, in update_dict dictionary_power_readings[time.time()] = ApparentPower UnboundLocalError: local variable 'dictionary_power_readings' referenced before assignment


Tags: 代码infrompydictionarytimelineupdate
2条回答
dictionary_power_readings = {}

def update_dict():
    global dictionary_power_readings
    ApparentPower = "power"
    dictionary_power_readings[time.time()] = ApparentPower
    print(dictionary_power_readings)
    dictionary_power_readin

在函数中使用全局关键字

def update_dict():
     global dictionary_power_readings
     ApparentPower = "power"
     dictionary_power_readings[time.time()] = ApparentPower
     print(dictionary_power_readings)
     dictionary_power_readings ={} 

它有效,只要试一下就行了

相关问题 更多 >

    热门问题