使用另外两个变量引用python变量



我有固定的变量:

apple_weight = 50
mango_weight = 100
veggie1 = apple
veggie2 = mango

我希望能够通过使用我的代码中的素食变量来引用权重变量:

whatcomeshere = globals()[[str(veggie1) + str(_weight)]]
print("The weight of the veggie {}, is {}").format(veggie1, whatcomeshere)

我正试图使用上面的globals语句,但得到了以下错误:

Traceback (most recent call last):
File "<ipython-input-9-bceaa9070b38>", line 3, in <module>
veggie1 = apple
NameError: name 'apple' is not defined

applemango被解释为不存在的变量。您的意思是将它们定义为字符串文字。见下文:

apple_weight = 50
mango_weight = 100
veggie1 = 'apple'
veggie2 = 'mango'

您可能会发现,使用像字典这样的简单数据类型来封装此结构比使用全局命名空间更容易。

APPLE_CDE = 'apple'
MANGO_CDE = 'mango'
d = {
APPLE_CDE: {'weight': 50},
MANGO_CDE: {'weight': 100}
}
w = d.get(APPLE_CDE, {}).get('weight', None)
print(w)

您收到的错误是因为名称appleveggie1行中引用之前没有声明或定义。我想你希望veggie1是串苹果,所以你需要

veggie1 = "apple"

对于引用其他变量的问题,你不能像在中那样直接构建变量的名称

[str(veggie1) + str(_weight)]

编辑:skullgobil1089的答案展示了一个使用字典做你正在做的事情的好方法

这将返回的是[apple50],我想这不是你想要的。您需要显式调用apple_weight

如果要生成变量名,则需要使用字典,然后生成字符串作为字典的键。

https://www.w3schools.com/python/python_dictionaries.asp

最新更新