基本上它應該採用一組座標並返回其鄰居的座標列表。然而,當它擊中的位置:爲什麼這段代碼返回一個列表索引錯誤?
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
時i
爲2,它給了我一個了指數的錯誤。我可以設法讓它打印結果[2] [0],但是在if語句中拋出錯誤。這是爲什麼發生?
def neighborGen(row,col,board):
"""
returns lists of coords of neighbors, in order of up, down, left, right
"""
result = []
result.append([row-1 , col])
result.append([row+1 , col])
result.append([row , col-1])
result.append([row , col+1])
#prune off invalid neighbors (such as (0,-1), etc etc)
for i in range(len(result)):
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
if result[i][1] < 0 or result[i][1] >= board.dimensions:
result.pop(i)
return result
我應該用這段代碼替換整個for循環嗎?我在理解語法方面有點麻煩。 – mmmeff 2010-12-21 05:18:49
是的,它取代了整個for循環。 http://docs.python.org/tutorial/datastructures.html#list-comprehensions – 2010-12-21 05:19:40
非常感謝您的救命!此外,鏈接到pydocs頁面是一個真棒觸摸。祝你有愉快的一天。 – mmmeff 2010-12-21 05:20:17