问题描述
限时送ChatGPT账号..我是 Python 新手,所以我不知道这是否可行.我正在尝试从字符串列表中创建变量名称列表,以便我可以为新创建的变量赋值.
我看到另一个类似的问题,但已经有一个键和值的 dict pays.
这是我的代码:
def 方便(自我):a = raw_input('多少手?')对于范围内的 i(int(a)):h = "手" + str(i+ 1)self.list_of_hands.append(h)# 想从 self.list_of_hands 创建变量名# 类似于hand1 = self.do_something(i)"打印 h打印 self.list_of_hands
鉴于一些答案,我添加以下评论:然后我将把字典分配给每个变量.那么,我可以创建字典字典吗?
解决方案为什么不直接使用字符串作为键来构建字典?
<预><代码>>>>类测试():def方便(自我):a = raw_input('多少手?')d = { "hand" + str(i + 1) : self.do_something(i) for i in range(int(a)) }键 = d.keys()键.排序()对于键中的 x:打印 x, '=', d[x]def do_something(self, i):返回某物"+ str(i)>>>测试().方便()几只手?4手 1 = 东西 0手 2 = 东西 1手 3 = 东西 2手 4 = 东西 3您更新了问题以询问是否可以将字典作为值存储在字典中.是的,您可以:
<预><代码>>>>d = { i : { j : str(i) + str(j) for j in range(5) } for i in range(5) }>>>d[1][2]'12'>>>d[4][1]'41'>>>d[2]{0:'20',1:'21',2:'22',3:'23',4:'24'}>>d[5] = { 1 : '51' }>>d[5][1]'51'I'm new to python, so I don't know if this is possible. I'm trying to create a list of variable names from a list of strings so I can then assign values to the newly created variables.
I saw another similar question, but there was already a dict pays of keys and values.
Here's my code:
def handy(self):
a = raw_input('How many hands? ')
for i in range(int(a)):
h = "hand" + str(i+ 1)
self.list_of_hands.append(h)
# would like to create variable names from self.list_of_hands
# something like "hand1 = self.do_something(i)"
print h
print self.list_of_hands
Given some of the answers, i'm adding the following comment: I'm going to then assign dicts to each variable. So, can I create a dictionary of dictionaries?
解决方案Why don't you just construct a dictionary using the strings as keys?
>>> class test():
def handy(self):
a = raw_input('How many hands? ')
d = { "hand" + str(i + 1) : self.do_something(i) for i in range(int(a)) }
keys = d.keys()
keys.sort()
for x in keys:
print x, '=', d[x]
def do_something(self, i):
return "something " + str(i)
>>> test().handy()
How many hands? 4
hand1 = something 0
hand2 = something 1
hand3 = something 2
hand4 = something 3
Edit: You updated the question to ask if you can store a dictionary as a value in a dictionary. Yes, you can:
>>> d = { i : { j : str(i) + str(j) for j in range(5) } for i in range(5) }
>>> d[1][2]
'12'
>>> d[4][1]
'41'
>>> d[2]
{0: '20', 1: '21', 2: '22', 3: '23', 4: '24'}
>> d[5] = { 1 : '51' }
>> d[5][1]
'51'
这篇关于Python:可以从字符串列表中创建新的变量名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论