我试图在python中将字符串转换为整数,但它不允许m

2024-10-03 06:21:50 发布

您现在位置:Python中文网/ 问答频道 /正文

#itemsInExistence defined here:
itemName = input("What do you want the new item to be called? ")
itemStats = int(input("What is its stat? "))
itemAmount = int(input("How many of it are there? "))
itemRank = int(input("What is its base rank? "))
itemStats = int(itemStats)
itemAmount = int(itemAmount)
itemRank = int(itemRank)
for i in range(itemAmount):
  itemsInExistence.append([itemName, itemStats, itemAmount, itemRank])

#an Item is randomly chosen from itemsInExistence here:
gains = random.randint(1, 5)
if gains == 2:
  gained_weapon = random.choice(itemsInExistence)
  print("You gained the item", gained_weapon)
  itemMatrix.append(gained_weapon)
  for i, item in enumerate(itemsInExistence):
    if gained_weapon == itemsInExistence[i]:
      del itemsInExistence[i]
      break

#Here I am attempting to add what was previously known as itemStats of the 2 items together:
print("Choose two items to craft with by selecting the number to the left of it. Remember 
their 3rd numbers have to match!")
item1 = input("Item 1: ")
item2 = input("Item 2: ")
item1 = int(item1)
item2 = int(item2)
--itemMatrix[item1][-5] = int(itemMatrix[item1][-5])--
#The error occurs on the line above
itemMatrix[item1][-5] += int(itemMatrix[item2][-5])

itemMatrix[item1]看起来像['Name',1,3,1]

项矩阵[item1][-5]看起来像3

不管我怎么尝试,它总是说“str不支持该项分配/操作”。有什么办法可以解决这个问题吗?你知道吗

谢谢你抽出时间!你知道吗


Tags: thetoinputitemwhatintweaponitem1
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:50

这将不是一个完美的解决方案,但它肯定会帮助你很多!你知道吗

使用字典来管理游戏数据,这将使事情变得更简单:

items_in_existence = []

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'])):
    items_in_existence.append(item)

通过这种方式,您可以直接使用属性名称,而不是使用数字来访问项目的属性:

for item in items_in_existence:
    print(item['name'], item['rank'])

相关问题 更多 >