【问题标题】:How to use string value as a variable name in Python? [duplicate]如何在 Python 中使用字符串值作为变量名? [复制]
【发布时间】:2016-10-09 14:41:26
【问题描述】:

假设我有如下列表:

candy = ['a','b','c']
fruit = ['d','e','f']
snack = ['g','h','i']

还有一个字符串

name = 'fruit'

我想使用字符串name 来访问列表及其内容。在这种情况下,它应该是fruit。我将使用name 来迭代列表。如:

for x in name:
    print x

【问题讨论】:

  • 您可以使用 eval 执行此操作,但我建议您使用字典来保存这些列表。
  • 更加强调:你不要在python中使用字符串值作为变量名。 Python 拥有强大的工具和数据结构,请使用它们。
  • @spectras 请给我参考我可以使用的数据结构来代替它。

标签: python string python-2.7 variables


【解决方案1】:

我不明白您这样做究竟想达到什么目的,但这可以使用eval 来完成。我不建议使用eval。如果你告诉我们你最终想要达到的目标会更好。

>>> candy = ['a','b','c']
>>> fruit = ['d','e','f']
>>> snack = ['g','h','i']
>>> name = 'fruit'
>>> eval(name)
['d', 'e', 'f']  

编辑

看看 Sнаđошƒаӽ 的另一个答案。这将是更好的方式。 eval 存在安全风险,不推荐使用。

【讨论】:

    【解决方案2】:

    使用字典!

    my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit'
                       'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a , 
                 'candy' : ['a','b','c']           ,
                          'snack' : ['g','h','i']
        }
    
    print my_dictionary['fruit'] # how to access a dictionary.
    for key in my_dictionary:
        print key #how to iterate through a dictionary, each iteration will give you the next key
        print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following!
    
    for key, value in my_dictionary.iteritems():
        print key, value #where key is the key and value is the value associated with key
    
    print my_dictionary.keys() #list of keys for a dict
    print my_dictionary.values() #list of values for a dict
    

    默认情况下字典没有排序,这可能会导致问题,但是有一些方法可以使用多维数组或orderedDicts,但我们将在以后保存它! 我希望这会有所帮助!

    【讨论】:

    • 有时最好的答案是最难使用的:-)
    • @BhargavRao 但通常情况下,最简单的答案最难接受!
    • 在我的答案已经发布后,您的答案已被编辑为包含一个字典。至于信息,我只是试图解释使用字典的优点和缺点。
    【解决方案3】:

    你可以像这样使用globals():

    for e in globals()[name]:
        print(e)
    

    输出:

    d
    e
    f
    

    如果您的变量恰好在某个本地范围内,您可以使用locals()

    或您可以创建字典并访问它:

    d = {'candy': candy, 'fruit': fruit, 'snack': snack}
    name = 'fruit'
    
    for e in d[name]:
        print(e)
    

    【讨论】:

    • 说真的,请使用它而不是eval,尤其是如果传入的值来自用户 - 这让用户可以有效地运行所有存在巨大安全风险的东西.虽然使用dict 会更好。
    • @metatoaster 我认为您的评论应该针对 OP 的问题,您不觉得吗? ;-) 谢谢。
    • 确实如此。但是这个问题和它的答案是一个教科书式的例子,给一个询问如何在脚上开枪的人提供详细的解释。
    • 使用globals() 是个好主意。
    • @MuhammadYaseenKhan> 不,不是。它公开了许多变量,包括导入的模块和内部 python 变量。只是为了得到一本字典,那么为什么不首先使用字典呢?这就是他们的目的。
    猜你喜欢
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2017-02-05
    • 1970-01-01
    相关资源
    最近更新 更多