Python将字符串转换为变量名 [英] Python convert string to variable name

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

问题描述

我知道这可能是重复的,但到目前为止,我还没有找到(或应该被理解)对我所寻找的答案。

Im aware that this may come up as a duplicate but so far I haven't found (or should that be understood) an answer to what Im looking for.

我有一个字符串列表,并希望将每个字符串转换为一个变量名称,然后我分配一些东西。我明白,我可能需要一个dict,但我不熟悉他们,因为我比较新的python,所有的例子,我看到迄今为止处理价值观,而我正在尝试不同的东西。

I have a list of strings and want to convert each one into a variable name which I then assign something to. I understand that I may need a dict for this but I am unfamiliar with them as I am relatively new to python and all the examples I have seen so far deal with values whilst I'm trying something different.

我的东西如下:

list = ['spam', 'eggs', 'ham']

for i in range(len(list)):
    list[i] = rat.readColumn(ratDataset, list[i])

其中第一个列表[i]是变量名,而不是字符串。第二个列表[i]是一个字符串(并且上下文是从栅格属性表(大鼠)读取的列的名称)

where the first list[i] is a variable name and not a string. The second list[i] is a string (and for context is the name of a column Im reading from a raster attribute table (rat))

本质上我想要每个字符串在列表中设置为变量名称。

Essentially I want each string within the list to be set as a variable name.

这个想法是我可以创建一个循环,而不必为每个变量写出行,与匹配的鼠标列名称(字符串)。也许有一种比我建议的啤酒方法要好吗?

The idea behind this is that I can create a loop without having to write out the line for each variable I want, with matching rat column name (the string). Maybe there is a beer way of doing this than I am suggesting?

推荐答案

尝试以下操作:

lst = ['spam', 'eggs', 'ham']
d = {}   # empty dictionary
for name in lst:
    d[name] = rat.readColumn(ratDataset, name)

不要使用 list 作为标识符,因为它是一个类型标识符,你将掩盖它的存在。 for循环可以直接为内部的元素进行迭代,不需要构造索引并使用它来代替列表。 d ['spam'] 将是您的变量之一。

Do not use list for your identifiers as it is a type identifier and you would mask its existence. The for loop can iterate directly for the elements inside -- no need to construct index and use it aganist the list. The d['spam'] will be one of your variables.

尽管,也可以创建真实变量名称,如 spam eggs ham ,你不会这样做,因为效果将是无用的。

Although, it is also possible to create the real variable names like spam, eggs, ham, you would not probably do that as the effect would be useless.

这篇关于Python将字符串转换为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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