将字典保存到列表中而又不损失其值

itemsInExistence = []
item = {}
item['name'] = input("What do you want the new item to be called? ")
item['stats'] = int(input("What is its stat? "))
item['rank'] = int(input("What is its base rank? "))
item['amount'] = int(input("How many of it are there? "))
for i in range(item['amount']):
    itemsInExistence.append(item)

稍后在代码中...

gains = random.randint(1,5)
if gains == 2:
  x = -1
  for i in itemsInExistence:
    x += 1
    print(x)
  gained_weapon = random.randint(0,x)
  print(gained_weapon)
  print("You gained the item",itemsInExistence[gained_weapon])
  itemMatrix.append(itemsInExistence[gained_weapon])
  print(itemMatrix)
  for i,item in enumerate(itemsInExistence):
    if gained_weapon == itemsInExistence[i]:
      del itemsInExistence[i]
      break

将项目附加到itemMatrix后,它变成一个字符串。这是一个问题,因为在这些值过时之后,我需要更改item['rank']item['stats']item['amount']的值。而且通过itemMatrix[num][-num]获取值是行不通的,它不会让我将其从字符串更改为整数。

shndebb 回答:将字典保存到列表中而又不损失其值

我不确定您所指的项目是不是一个字符串。您发布的代码将导致itemsInExistence是一个包含数量等于值item['ammount']的字典的列表。

例如:

[
    {'name': 'Ball','stats': 1,'rank': 1,'amount': 2},{'name': 'Ball','amount': 2}
]

通过itemsInExistence[0]['rank']可以访问此列表中的项目,并相应地更改整数和字符串以访问所需的数据。

itemsInExistence[1]['rank'] = 4

然后会给您这样的清单。

[
    {'name': 'Ball','rank': 4,'amount': 2}
]

更新 要访问itemMatrix内部的数据,与上面的

相同
itemMatrix[-1]['rank'] = 10
# -1 accesses the last item in the list

所以,如果您有类似的东西

if gains == 2:
    x = len(itemsInExistence) -1
    gained_weapon = random.randint(0,x)

    print("You gained the item",itemsInExistence[gained_weapon])

    itemMatrix.append(itemsInExistence[gained_weapon])

    print(itemMatrix)

    itemMatrix[-1]['rank'] = 10

    print(itemMatrix)

您将获得以下内容

What do you want the new item to be called? a
What is its stat? 1
What is its base rank? 2
How many of it are there? 3
You gained the item {'name': 'a','rank': 2,'amount': 3}
[{'name': 'a','amount': 3}]
[{'name': 'a','rank': 10,'amount': 3}]
本文链接:https://www.f2er.com/3136808.html

大家都在问