尝试从python中的列表调用索引时出错

2024-05-28 20:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个庞大的列表,我正在尝试创建一个函数来打印数据集[51],它是:

['X', ['Sheet A', 'Location 1', 'Upright'],
          ['Sheet B', 'Location 2', 'Upright'],
          ['Sheet C', 'Location 3', 'Upright'],
          ['Sheet D', 'Location 4', 'Upright']],

这行如果第51张名单里面有第一批名单

这是我的代码,它上面有所有的功能来绘制图纸

^{pr2}$

但是我得到了这个错误,我不知道为什么,我试图改变索引或使用[51][1],但它没有改变结果

Traceback (most recent call last):
  File "/Users/chalysefoster/Documents/2017/QUT Semester 2/IFB104 Building IT Systems/Assigment 1/billboard.py", line 911, in <module>
    paste_up(data_sets[51])
  File "/Users/chalysefoster/Documents/2017/QUT Semester 2/IFB104 Building IT Systems/Assigment 1/billboard.py", line 883, in paste_up
    if position[1] == "Location 1":
IndexError: list index out of range

谢谢


Tags: itlocationusersdocumentsfilesheetsystemsbuilding
1条回答
网友
1楼 · 发布于 2024-05-28 20:10:30

据我所知-您收到索引器错误是因为提供的列表中的第一个元素只包含一个索引为0的元素(显然),所以当您尝试访问el[1]时,会引发IndexError。在

>>>for i, element in enumerate(data_sets):
    print(i, element)

0 X
1 ['Sheet A', 'Location 1', 'Upright']
2 ['Sheet B', 'Location 2', 'Upright']
3 ['Sheet C', 'Location 3', 'Upright']
4 ['Sheet D', 'Location 4', 'Upright']

我想这很清楚你为什么会得到索引器。在

在开始对数据集进行赋值后,只需添加如下内容:

^{pr2}$

顺便说一句,使用字典比多个if-elif语句更清楚:

def paste_up(data):

    sheets = {
        "Sheet A": draw_sheetA,
        "Sheet B": draw_sheetB,
        "Sheet C": draw_sheetC,
        "Sheet D": draw_sheetD
    }

    locations = {
        "Location 1": (-300, 0),
        "Location 2": (-100, 0),
        "Location 3": (100, 0),
        "Location 4": (300, 0)
    }

    directions = {
        "Upright": (90),
        "Upside down": (270)
    }

    for item in data:

        if len(item) != 3 and not isinstance(item, list):
            # continue or raise ValueError ( for example )
            continue

        # retrieve data
        sheet, location, direction = item

        # get link to fucntion from dictionary
        draw_action = sheets[sheet]

        # get start position from dictionary
        start_position = locations[location]

        # get start direction from dictionary
        start_direction = directions[direction]

        # exec function with found args
        draw_action(start_position, start_direction)

相关问题 更多 >

    热门问题