嵌套For循环生成'列表索引超出范围'错误

时间:2016-12-07 05:48:31

标签: python indexing

我试图创建一组坐标,存储在一个字典中(每一对都有一个密钥,此刻每次迭代增加1)。盯着代码并手动操作每一步的组合让我迷失方向,如果有人能告诉我我的错误在哪里,那就太棒了。

column = [100, 200, 300, 400, 500, 600]
row = [100, 200, 300, 400, 500, 600, 700]
slotcounter = 0
slotdict = {}
for j in row: 
    for i in column: 
        slotcounter += 1
        coordinate = [row[j],column[i]]
        slotdict[coordinate] = slotcounter
        #print(slotdict)

3 个答案:

答案 0 :(得分:0)

你可以尝试:

for j_index, j_value in enumerate(row): 
    for i_index,i_value in enumerate(column):
       .....
       # and here you can access indexes as well as value.

for j in range(len(row)): 
    for i in range(len(column)) :
       ...
       # here you can access indexes & by using row[j] you can get value.

答案 1 :(得分:0)

要使代码正常工作,您可以这样做:

for j in row:
    for i in column:
        slotcounter+=1
        coordinate = [j,i]
        slotdict[slotcounter] = coordinate

我不确定这是不是你所追求的,因为它给你一本包含42把钥匙的字典。

答案 2 :(得分:0)

其他人已经提到过为什么你的代码没有做你想做的事情。请注意,itertools.product会为您生成对:

from itertools import product

column = [100, 200, 300, 400, 500, 600]
row = [100, 200, 300, 400, 500, 600, 700]
slotcounter = 0
slotdict = {}
for coordinate in product(column, row):
   slotcounter += 1
   slotdict[coordinate] = slotcounter

编辑 - 使用枚举和字典理解,这可以作为单个表达式完成:

slotdict = {
    coord: counter for counter, coord in enumerate(product(
        [100, 200, 300, 400, 500, 600],
        [100, 200, 300, 400, 500, 600, 700]))
}