为什么这段代码会先打印一堆空列表,然后再显示IndexError?

时间:2019-07-25 19:57:54

标签: python list for-loop

我正在遍历一个由以下组成的列表(它可能看起来没有组织,但是有原因):菜名,配料编号,所有者,配料1,配料说明1,配料2,配料说明2 ,配料3 ...等。每道菜可能含有不同数量的配料,但是配料的数量始终在菜名后面的索引上。以下是称为书的列表:

['pbj', 3, 'Alex', 'peanutbutter', 'Nice and Creamy', 'jelly', 
'Make sure it is refridgerated', 'bread', 'Whole wheat', 'Spaghetti', 
2, 'Ryan', 'noodles', 'Spaghetti shaped', 'tomato sauce', 'Smooth, not chunky',
'Grilled Cheese', 2, 'Jason', 'Cheese', 'Any kind of cheese', 'bread', 
'Any kind of bread']

我得到了几个列表的输出,然后是一个IndexError。

我尝试逐步了解过程中发生的事情,但我仍然不明白问题所在。

numDish = 3 

m = 0
for i in range (numDish): # for each unique dish
    k = m + 3
    print(book[m: k]) #prints dish, # of ingredients, and owner

    for j in range(int(book[m + 1])): #run for each ingredient per dish
        print(book[k: k + 2]) #print ingredient and associated description
        k += 2 
    print ('\n')
    m = k + 1 #Set m to the value after the last description

我希望并希望结果打印为:

'pbj', 3, 'Alex'
'peanutbutter', 'Nice and Creamy', 
'jelly', 'Make sure it is refridgerated', 
'bread', 'Whole wheat', 

'Spaghetti', 2, 'Ryan', 
'noodles', 'Spaghetti shaped', 
'tomato sauce', 'Smooth, not chunky', 

'Grilled Cheese', 2, 'Jason', 
'Cheese', 'Any kind of cheese', 
'bread', 'Any kind of bread'

(我不确定是否要加引号,但这对我来说无关紧要。)

相反,我得到了:

['pbj', 3, 'Alex']
['peanutbutter', 'Nice and Creamy']
['jelly', 'Make sure it is refridgerated']
['bread', 'Whole wheat']
[2, 'Ryan', 'noodles']
  

回溯(最近通话最近一次):

     

文件“”,第1行,在    runfile('C:/Users/CSANCH08/Desktop/untitled2.py',wdir ='C:/ Users / CSANCH08 / Desktop')

     

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py”,行786,在运行文件中     execfile(文件名,命名空间)

     

exec文件中的第110行,文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py”     exec(compile(f.read(),文件名,'exec'),命名空间)

     

第22行中的文件“ C:/Users/CSANCH08/Desktop/untitled2.py”   对于范围(int(book [m + 1]))中的j:#run每盘每种成分

     

ValueError:以10为底的'int()'的无效文字:'Ryan'

1 个答案:

答案 0 :(得分:1)

book = ['pbj', 3, 'Alex', 'peanutbutter', 'Nice and Creamy', 'jelly', 'Make sure >it is refridgerated', 'bread', 'Whole wheat', 'Spaghetti', 2, 'Ryan', 'noodles', 'Spaghetti shaped', 'tomato sauce', 'Smooth, not >chunky', 'Grilled Cheese', 2, 'Jason', 'Cheese', 'Any kind of >cheese', 'bread', 'Any kind of bread']
numDish = 3 

m = 0
for i in range (numDish): # for each unique dish
    k = m + 3
    print(book[m: k]) #prints dish, # of ingredients, and owner

    for j in range(int(book[m + 1])): #run for each ingredient per dish
        print(book[k: k + 2]) #print ingredient and associated description
        k += 2 
    print ('\n')
    m = k 

在最后一行将m = k + 1更改为m = k。