从python中的两个字符串创建变量名 [英] Create variable name from two string in python

查看:37
本文介绍了从python中的两个字符串创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望从 Python 中的两个字符串创建一个变量名,例如:

I am looking to create a variable name from two strings in Python, e.g.:

 a = "column_number"
 b = "_url1"

然后能够得到一个我可以使用的变量名"column_number_url1".

and then be able to get a variable name "column_number_url1" that I can use.

我明白这通常不是一个好主意 - 有很多帖子解释了为什么这是一个坏主意(例如 如何创建可变数量的变量? , 创建多个变量 ) - 我主要希望能够做到这一点,因为这些都是在代码中的其他地方定义的所有变量,并且想要一种能够重新访问它们的简单方法(即而不是创建数千个唯一变量,我同意字典等会更好).

I appreciate this is in general not a good idea - there are numerous posts which go into why it is a bad idea (e.g. How do I create a variable number of variables? , Creating multiple variables ) - I mainly want to be able to do it because these are all variables which get defined elsewhere in the code, and want a easy way of being able to re-access them (i.e. rather than to create thousands of unique variables, which I agree a dictionary etc. would be better for).

据我所知,我在其他帖子中找到的答案都是执行此操作的替代方法,而不是如何从两个字符串创建变量名称.

As far as I can tell, the answers in the other posts I have found are all alternative ways of doing this, rather than how to create a variable name from two strings.

推荐答案

>>> a = "column_number"
>>> b = "_url1"
>>> x = 1234
>>> globals()[a + b] = x
>>> column_number_url1
1234

没有多少帖子解释如何执行此操作的原因是(正如您可能已经收集到的)不是一个好主意.我保证您的用例也不例外.

The reason that there aren't many posts explaining how to do this is because (as you might have gathered) it's not a good idea. I guarantee that your use case is no exception.

如果您没有注意到,globals() 本质上是一个全局变量字典.这意味着你应该一直使用字典;)

In case you didn't notice, globals() is essentially a dictionary of global variables. Which implies that you should be using a dictionary for this all along ;)

这篇关于从python中的两个字符串创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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