python字符串转变量名_Python将字符串转换为变量名

1586010002-jmsa.png

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.

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.

Im after something like:

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

for i in range(len(list)):

list[i] = rat.readColumn(ratDataset, list[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?

解决方案

Try the following:

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

d = {} # empty dictionary

for name in lst:

d[name] = rat.readColumn(ratDataset, name)

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值