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

2024-06-21 20:20:11 发布

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

我想做一个函数来打印这个巨大列表中的数据集。但是,当我尝试运行它时,出现了一个错误:

line 460, in paste_up
for items in sublist[1]:
IndexError: list index out of range

我的函数粘贴如下所示:

# Paste the sheets onto the billboard as per the provided data set
def paste_up(data):
   for sublist in data_sets:
       for items in sublist[1]:
        if item[0] == 'Sheet A':
            Sheet_A( item[1], item[2])
        elif item[0] == 'Sheet B':
            Sheet_B( item[1], item[2])
        elif item[0] == 'Sheet C':
            Sheet_C( item[1], item[2])
        elif item[0] == 'Sheet D':
            Sheet_D( item[1], item[2])

我要测试的列表是:

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

任何帮助都将不胜感激

编辑。。。。。 有问题的功能,现在无休止地画的图像,我试图得到打印。下面是我的函数的一个例子,它在一个特定的位置绘制一个200x500的矩形

#draw the Sheets and the images on them.
def Sheet_A(location, orientation):
    #code for location and orientation of Sheet_A.
    if location == 'location 1':
        if orientation == 'upright': goto(-300,0);setheading(0)
        elif orientation == 'upside down': goto(-300,0);setheading(180)

    elif location == 'location 2':
        if orientation == 'upright':goto(-100,0);setheading(0)
        elif orientation =='upside down': goto(-100,0);setheading(180)

    elif location == 'location 3':
        if orientation == 'upright':goto(100,0);setheading(0)
        elif orientation == 'Upside down':goto(100,0);setheading(180)

    elif location == 'location 4':    
        if orientation == 'upright':goto(300,0);setheading(0)
        elif orientation == 'Upside down':goto(300,0);setheading(180)

    #drawing Sheet_A outline and filling the background.
    width(3);penup();begin_fill();forward(100);pendown();right(90)
    forward(250);right(90);forward(200);right(90);forward(500);right(90)
    forward(200);right(90);forward(250);color('blue');end_fill();color('black');penup()

Tags: theinrightforiflocationitemsheet
1条回答
网友
1楼 · 发布于 2024-06-21 20:20:11

首先把for items...改成for item...

你的代码应该是这样的:

for sublist in data_sets:
    for item in sublist[1:]:
        if item[0] == 'Sheet A':
            Sheet_A( item[1], item[2])
        elif item[0] == 'Sheet B':
            Sheet_B( item[1], item[2])
        elif item[0] == 'Sheet C':
            Sheet_C( item[1], item[2])
        elif item[0] == 'Sheet D':
            Sheet_D( item[1], item[2])

如果您的数据如下所示:

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

相关问题 更多 >