如何在Python中使用字符串值作为变量名?

2024-04-18 00:54:57 发布

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

假设我有如下清单:

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

还有一根绳子

name = 'fruit'

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

for x in name:
    print x

Tags: 字符串namein内容列表for情况print
3条回答

您可以像这样使用^{}

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

输出:

d
e
f

如果变量恰好在某个局部作用域中,则可以使用^{}

您可以创建字典并访问:

d = {'candy': candy, 'fruit': fruit, 'snack': snack}
name = 'fruit'

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

用字典!

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来解决这个问题,但是我们将在以后保存它! 我希望这有帮助!

我不明白你到底想通过这样做来达到什么目的,但这可以通过使用eval来实现。不过,我不建议使用eval。如果你能告诉我们你最终想要达到的目标会更好。

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

编辑

看看Sааааааааааааааа。这样会更好。eval有安全风险,我不建议使用它。

相关问题 更多 >

    热门问题