基本上它应该采用一组坐标并返回其邻居的坐标列表。然而,当它击中的位置:为什么这段代码返回一个列表索引错误?
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