gpt4 book ai didi

python - 从列表中的单个元素中减去?

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:07 24 4
gpt4 key购买 nike

我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com