我正在尝试将字符串转换为python中的整数,但不会让我

时间:2019-11-07 18:09:56

标签: python string

#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]

itemMatrix [item1] [-5]看起来像3

无论我尝试什么,它总是说“ str不支持该项目的分配/操作”。有什么办法可以解决这个问题?

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

那不是一个完美的解决方案,但肯定会对您有很大帮助!

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

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'])