[英]Saving a Dictionary to a List Without the Dictionary Losing its Value
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
當 item 附加到itemMatrix
時,它變成一個字符串。 這是一個問題,因為我需要在item['rank']
、 item['stats']
和item['amount']
的值過時后更改這些值。 通過itemMatrix[num][-num]
獲取值不起作用,它不會讓我將它從字符串更改為 integer。
我不完全確定您所說的 item 變成一個字符串是什么意思。 您發布的代碼將導致itemsInExistence
是一個列表,其中包含許多等於值item['ammount']
的字典。
例如:
[
{'name': 'Ball', 'stats': 1, 'rank': 1, 'amount': 2},
{'name': 'Ball', 'stats': 1, 'rank': 1, 'amount': 2}
]
訪問此列表中的項目將由itemsInExistence[0]['rank']
完成,相應地更改 integer 和字符串以訪問所需的數據。
itemsInExistence[1]['rank'] = 4
然后會給你這樣的列表。
[
{'name': 'Ball', 'stats': 1, 'rank': 4, 'amount': 2},
{'name': 'Ball', 'stats': 1, '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', 'stats': 1, 'rank': 2, 'amount': 3}
[{'name': 'a', 'stats': 1, 'rank': 2, 'amount': 3}]
[{'name': 'a', 'stats': 1, 'rank': 10, 'amount': 3}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.