【问题标题】:Assigning Variable with Value of Existing Variable from String Value [duplicate]用字符串值中的现有变量的值分配变量[重复]
【发布时间】:2016-07-24 14:08:00
【问题描述】:

我有大量可变形式的数据:

abc_123 = 5  
def_456 = 7  
ghi_789 = 9 

等等

我向用户询问各种输入,这些输入构建了一个字符串。例如:

temp = "abc_123"

如何使 temp = abc_123,从而使 temp = 5?

【问题讨论】:

  • 不要使用变量变量,使用字典。

标签: python string variables variable-assignment


【解决方案1】:

制作一个字典,然后按键查找值:

>>> d = {"abc_123": 5, "def_456": 7, "ghi_789": 9}
>>> temp = "abc_123"
>>> d[temp]
5
>>> d.get("invalid", "not found")
'not found'

【讨论】:

  • 谢谢!那效果很好。以这种格式重新排列所有数据需要一些时间,但仅仅为此编写代码还不够痛苦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多