【问题标题】:Python: use a string as a variable?Python:使用字符串作为变量?
【发布时间】:2012-04-15 04:56:45
【问题描述】:

我想编写一个 python 脚本,一次创建多个字典,然后将字典打印出来,但我不知道如何将字符串转换为变量。

number = 0

while (number < 10):
    number = number + 1
    dictionarynumber = ("D"+str(number)) # creates the dictionarys name(D1,D2,D3,D4,D5,D6,D7,D8,D9,D10)
    var(dictionarynumber) = {"Fruit":"Apple","Book":"Oliver Twist","Building":"White House"} #Of course var() doesn't work but I placed it here to get my point across
    print(dictionarynumber)

回答后:

我喜欢关于字典的想法,去掉不需要的“D”是有道理的。小伙伴们对此怎么看?

dict = {}
n = 0

while (n < 10):
    n = n + 1
    d = n
    d = {"Key":"Information"}
    dict[n] = d

print(dict)


# Output = 
#          {1: {'Key': 'Information'},
#           2: {'Key': 'Information'},
#           3: {'Key': 'Information'},
#           4: {'Key': 'Information'},
#           5: {'Key': 'Information'},
#           6: {'Key': 'Information'},
#           7: {'Key': 'Information'},
#           8: {'Key': 'Information'},
#           9: {'Key': 'Information'},
#           10: {'Key': 'Information'}}

【问题讨论】:

  • 使用列表(在索引器中去掉“D”)或其他字典。以后你会感谢自己的。
  • 如果您希望能够任意命名它们而不是仅使用序列号,则可以使用字典字典 - 计算的键仍然比计算机名称更好。
  • 你的 number 循环应该是:for number in range(1, 11):
  • 是的,你可以疯狂地使用字典。 ({1: {'a': {'i': 1, 'ii': 2), 'b': 3}, 2: 4, 3: {'knight': 'ni', 'parrot': None}} 只是不要尝试使用字典作为键。

标签: python string variables


【解决方案1】:

如果你想给每个字典一个名字,把它们放在字典里。

dicts = {}
# dict_list = []
for i in xrange(10):
    dictionary_key = ('d{0}'.format(i))
    dict_item = {"Fruit":"Apple","Book":"Oliver Twist","Building":"White House"}
    dicts[dictionary_key] = dict_item
    # dict_list.append(dict_item)

如果您不想为您的字典使用名称,请将它们放在一个列表中。

【讨论】:

  • 一本空白字典,我不知道你能做到。似乎是个好主意。
【解决方案2】:

您似乎正在尝试创建混合数据类型,但我不清楚您想要什么样的结构,所以我会给您 2 个答案,希望一个是正确的。

第一,如果你想创建一堆字典并打印出来,你可以这样做:

diclist = [{"Fruit":"Apple"},{"Book":"Oliver Twist"},{"Building":"White House"}]
print(diclist[1])

第二,按照您给出的示例,您可能旨在创建一个列表字典。例如

listDic = {'Fruit':['Apples', 'Bannanas', 'Durian'], 'Book':['Oliver Twist','Flashman', 'Catch 22']}
print (listDic)

你可以像这样访问它:

print(listDic['Fruit'])

会导致

['苹果'、'香蕉'、'榴莲']

还有这个 打印(listDic['水果'][1]) 会导致

香蕉

如果我错过了您想要的答案,或者您想了解更多详细信息,请发表评论。

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 2012-07-18
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多