繁体   English   中英

Python IndexError:列表索引超出范围(二维列表)

[英]Python IndexError: list index out of range (2D list)

我是 python 的新手,目前正在测试二维列表。

该程序使用 2d 列表来存储一周中每天 3 种面条的销售额。

此外,每天还会有一个列,存储每天的总销售额。

但是,我收到一个 IndexError ,我似乎无法弄清楚出了什么问题。

Sales = [[]]

def enterSales(arr):

    i = 0
    j = 0
    total_per_day = 0

    while i < 7:

        day = {
            0: "Monday",
            1: "Tuesday",
            2: "Wednesday",
            3: "Thursday",
            4: "Friday",
            5: "Saturday",
            6: "Sunday"
        }

        print("Enter " + day[i] + " sales for...")

        for j in range(3):

            noodle = {
                0: "Dried",
                1: "Dark",
                2: "Spicy",
            }

            arr[i].append(int(input(noodle[j] + " noodle: ")))

            # calculate total sales per day
            total_per_day += arr[i][j]

        arr[i].append(total_per_day)
        i += 1


def totalWeeklySales(arr):

    total_sales_per_week = 0

    for i in range(7):

        total_sales_per_week += arr[i][3]

    return total_sales_per_week


enterSales(Sales)
value = totalWeeklySales(Sales)
print("Total sales of the week is", value, ".")

在此处输入图像描述

在您的 for 循环中,您必须为每个i循环添加空列表。

在增加i之前添加以下行

arr[i].append(total_per_day) # after this line in your code
arr.append([])  #add this line

看起来问题出在您的销售列表中。 在每次迭代中,您都试图 append 在Sales的第 i 个列表中添加一个新元素:

arr[i].append(int(input(noodle[j] + " noodle: ")))

由于您一开始就有Sales=[[],] 第一次迭代(i = 0)工作得很好。 第二个问题出现在第二个尝试访问 Sales[1] -> out of range 时,因为 Sales 只有 1 个元素。

由于您有 7 次迭代( while i < 7 )。 您可以按如下方式初始化您的销售:

Sales = [[] for x in range(7)]

这将导致Sales=[[], [], [], [], [], [], []]

我还建议您将 7 放在某个常量中,这样它的含义就更清楚了,您可以重复使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM