2016-12-07 127 views
1

我想创建一组坐标,存储在一本字典中(每对具有每次迭代增加1的关键字)。如果任何人都可以告诉我我的错误在哪里,那会很好,但是盯着代码和手动运行每一步的组合已经让我迷失了方向。嵌套For循环产生'列表索引超出范围'错误

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) 
+1

你迭代在你的列表中值,但你那么你尝试使用列表,就好像你通过索引迭代一样。你所需要的只是'coordinate = [j,i]'not'coordinate = [row [j],column [i]]',因为你按值重复,而不是索引。 –

+0

查看'enumermate' – staticor

+2

@staticor'enumerate':P – MYGz

回答

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. 
+3

如果使用得当,您的两个解决方案都可以使用。为什么只要按值迭代就可以解决所有这些问题?更不用说我更喜欢Pythonic了。 –

0

为了使您的代码的工作,你应该这样做:

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

我不是当然,如果这就是你想要的,因为它会给你一个42字典键。

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])) 
} 
+0

或者在'product'上使用'enumerate'来避免自己操作'slotcounter'。 – tripleee