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

标签 python

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

相关文章:

python - 在 Python 3 中将字符串转换为 int 或 float?

python - 如何在 scipy 稀疏矩阵上创建 View /python 引用?

python - 如何用正则表达式匹配一个不以 X 开头但以 Y 结尾的单词

python - 我如何在 Python `mysql_affected_rows()` 库中执行 `dataset`

python - 如何根据 python 中的优先级列表选择列中的元素?

Python 无法使用套接字绑定(bind)我的外部/公共(public) IP 地址,出现错误但是当使用本地 IP 地址时,错误不会出现

python:导出方法作为函数关闭对象

python - Gensim LdaMulticore 没有正确地进行多处理(仅使用 4 个 worker )

python - 在 Python 中使用 MatrixSymbol 简化矩阵表达式

python - 使用 python 解析 JSON 以根据条件获取值