如何在 Python 中使用字符串值作为变量名? [英] How to use string value as a variable name in Python?

查看:120
本文介绍了如何在 Python 中使用字符串值作为变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下列表:

candy = ['a','b','c']水果 = ['d','e','f']零食 = ['g','h','i']

和一个字符串

name = '水果'

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

 for x in name:打印 x

解决方案

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

<预><代码>>>>糖果 = ['a','b','c']>>>水果 = ['d','e','f']>>>零食 = ['g','h','i']>>>名称 = '水果'>>>评估(名称)['d', 'e', 'f']

编辑

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

Suppose I have lists as follows:

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

and a string

name = 'fruit'

I want to use string name for accessing list and it's content. In this case it should be fruit. I will use name for iterating list. As:

for x in name:
    print x

解决方案

I don't understand what exactly you're trying to achieve by doing this but this can be done using eval. I don't recommend using eval though. It'd be better if you tell us what you're trying to achieve finally.

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

EDIT

Look at the other answer by Sнаđошƒаӽ. It'll be better way to go. eval has security risk and I do not recommend its usage.

这篇关于如何在 Python 中使用字符串值作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆