我对 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
我想将 quantity[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
之前出现/p>
最佳答案
你可以使用增强赋值,-=
:
a[4] -= 3
或者只是将减法的结果重新分配回索引(无论如何 -=
都会这样做):
a[4] = a[4] - 3
关于python - 从列表中的单个元素中减去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34687393/