【问题标题】:IndexError: index 8 is out of bounds for axis 0 with size 8IndexError:索引 8 超出轴 0 的范围,大小为 8
【发布时间】:2019-10-13 12:10:29
【问题描述】:

我试图编写一个代码来显示每个项目的可用库存(stock_level)。 但是我收到了标题中提到的错误。 我正在将 txt 文件导入到数组中

code,description,stock_level,min_stock,max_stock,buying_price,selling_price
1,tukul,3,5,25,20.00,25.00
2,mouse,20,5,25,30.00,35.00
3,keyboard,2,5,25,30.00,35.00
4,headphone,20,5,25,100.00,105.00
5,monitor,1,5,25,150.00,155.00
6,cpu,20,5,25,700.00,705.00
7,casing,20,5,25,100.00,105.00

到目前为止,这是我的代码:

import numpy as np
import csv

list = np.zeros((7,8),dtype = str)
a = np.genfromtxt('stock.txt',delimiter = ',',dtype = str)
#print(a)

class stock:

    def __init__(self, code, description, stock_level, min_stock, max_stock, buying_price, selling_price):

        self.code = code
        self.description = description
        self.stock_level = stock_level

        self.min_stock = min_stock
        self.max_stock = max_stock
        self.buying_price = buying_price
        self.selling_price = selling_price

    def sell(stock):

        i = 0
        while i < 7:
            for r in a:
                r = 1
                for c in a:
                    print(a[r][1]," have ", a[r][2]," of stocks")
                    r += 1
            i += 1

disp = stock("","",0,0,0,0,0)
disp.display()
#disp.buy()
#disp.buy()
disp.sell()

问题出在函数 sell()

这是我得到的输出:

tukul  have  3  of stocks
mouse  have  20  of stocks
keyboard  have  2  of stocks
headphone  have  20  of stocks
monitor  have  1  of stocks
cpu  have  20  of stocks
casing  have  20  of stocks
Traceback (most recent call last):
  File "D:\OOP\Python\Kiosk\main.py", line 72, in <module>
    disp.sell()
  File "D:\OOP\Python\Kiosk\main.py", line 64, in sell
    print(a[r+1][1]," have ", a[r+1][2]," of stocks")
IndexError: index 8 is out of bounds for axis 0 with size 8
>>

我确实得到了我想要每个项目可用的库存清单的结果。但我不知道是什么导致了错误

【问题讨论】:

  • 阅读错误信息,非常直接。您无法查询 8 项列表中的第 9 项(人类说话)。
  • 谢谢我用范围函数解决了

标签: python


【解决方案1】:

大多数编程语言使用Zero based numbering。这意味着它们从 0 开始计数。例如,list[0] 指的是list 的第一项,list[7] 指的是第八项。当您引用 list[8] 时,您引用的是大小为 8 的数组的第 9 个元素,这会引发错误。

【讨论】:

    【解决方案2】:

    您的数组从索引 0 开始 因此,如果您尝试访问索引 8,这是不可能的,您需要一个大小为 9 的数组。 大小为 8 的数组的最大索引是 7。

    【讨论】:

      猜你喜欢
      • 2019-07-30
      • 2021-07-17
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2017-02-16
      • 2020-04-24
      • 2016-07-29
      • 2021-05-24
      相关资源
      最近更新 更多