2016-12-07 36 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

相關問題