2013-06-20 18 views
-7

因此,我正在製作波士頓地鐵站和其鄰居的字典,以製作更大的程序。每個電臺都屬於一條線路,如藍色或紅色,這些線路構成了波士頓整個地鐵系統。但我有麻煩。這裏是我的代碼到目前爲止:列表內容隨每次迭代而變化

for i in range(len(tuples)): 

    for x in range(len(tuples[i][1])): 

     print tuples 
     neighbors=[] 
     station=tuples[i][1][x] 
     if tuples[i][1][-1]==station and station not in duplicates: 
      line=0 
      for item in tuples: 
       if station in item[1]: 
        line=item[0] 
        break 
      neighbors.append((tuples[i][1][-2],line)) 
     elif tuples[i][1][0]==station and station not in duplicates: 
      line=0 
      for item in tuples: 
       if station in item[1]: 
        line=item[0] 
        break 
      neighbors.append((tuples[i][1][1],line)) 
     elif station in duplicates: 
      line=[] 
      for item in tuples: 
       if station in item[1]: 
        line.append((item[0],tuples.index(item))) 
      neighbors=[(tuples[i][1][x+1],tuples[i][1][x-1],line[0][0]),(tuples[line[1][1]][1][x+1],tuples[line[1][1]][1][x-1],line[1][0])] 
     else: 
      line=0 
      for item in tuples: 
       if station in item[1]: 
        line=item[0] 
        break 
      neighbors.append((tuples[i][1][x+1],tuples[i][1][x-1],line[0][0])) 
     for neighbor in neighbors: 
      subdict[station]={} 
      for i in range(len(neighbor)-1): 
       subdict[station].update({neighbor[i]:neighbor[-1]}) 

所以我跑了它,並得到一個語法錯誤,指出索引超出範圍錯誤。這沒有任何意義,但隨後我打印出單個工作站和列表中的元組,並發現它們不斷變化。因此,在一次迭代中,一條地鐵線路中的車站列表與預期相同,但之後則完全不同。只有一條地鐵線的名單中的第一站保持不變;其餘的來自波士頓地鐵的不同線路。

那麼有人可以告訴我在我的代碼中發生了什麼嗎?

+2

你有一些示例數據嗎?什麼線引發了錯誤?你爲什麼要通過索引迭代元組而不是直接遍歷元素? –

+0

你應該定義一個帶有線和鄰居屬性的「Station」類(鏈接站和方向列表)。鏈接列表應該比這些複雜的嵌套列表清單更適合於此類數據。 –

+0

請更詳細地說明錯誤的細節。 – icedwater

回答

2

我覺得你的問題是在最後幾行:

for i in range(len(tuples)): 
    for x in range(len(tuples[i][1])): 
     [...] 
     for neighbor in neighbors: 
      for i in range(len(neighbor)-1): #<- HERE 
      [...] 

你外環在可變i遍歷元組並存儲該索引的索引。最後的嵌套循環用另一個值覆蓋這個變量,這當然不是你想要的。

+0

這是另一個問題。發現得好! –

+0

那麼我的問題就解決了。謝謝。 –

2

沒有示例數據很難說,而且因爲您的數據結構乍看起來似乎非常複雜。

但有一件事,讓我懷疑:

  • 你在range(len(tuples[i][1]))迭代x
  • 然後你做neighbors=[(tuples[i][1][x+1],...)]

看起來很可能會拋出Index out of bounds異常。