我是Python的新手学习它是如何工作的这是我制作的一个程序,我似乎无法减少数量
如何从列表中的单个元素中减去特定数字?
import csv stockfile = open("Stock list.txt") csvf = csv.reader(stockfile,delimiter = ",") #Sets csvf vaiable to open text file #Delimiter is what seperates your values code = [] item = [] price = [] quantity = [] quantity = list(map(int, quantity)) for row in csvf: code.append(row[0]) item.append(row[1]) price.append(row[2]) quantity.append(row[3]) usersearch = input("Please enter a 7-digit code: ") #Asks the user to enter the unique item codes while usersearch not in code: print("This is not a valid 7-digit code") usersearch = input("Please enter a 7-digit code: ") if usersearch in code: print("The code has been found") index = code.index(usersearch) print("The item you have chosen is: %s"%item[index]) print("The price is: £%s"%price[index]) print("There are %s left in stock"%quantity[index]) quantity[index] -= 1
我想将数量[index]减少1
当我使用时,quantity[index] -= 1
我得到一个错误:
TypeError:不支持的操作数类型 - =:'str'和'int'
这些是文件的内容:
0000001,PS4,300,50
0000011,Xbox One,300,50
0000111,极品飞车,40,20
0001111,正当原因3,45,24
0011111,Dualshock 4,48,30
没关系,我想通了,quantity=list(map(int, quantity))
不得不在之前来quantity[index] -= 1
您可以使用扩充分配,-=
:
a[4] -= 3
或者只是将减法的结果重新分配回索引(-=
无论如何都是这样):
a[4] = a[4] - 3