发生错误的原因是您在每次迭代过程中都在迭代列表并删除元素。一般来说,修改您正在迭代的底层对象是危险的,无论您使用什么语言,都会导致有趣的错误。作为一个初学者,这是一个你应该避免的练习,除非你有一个很好的理由去做。
如前所述,创建基础列表的副本并从副本中删除元素,而不是从正在迭代的对象中删除元素,是避免这种情况的好方法。如果你这样做,
make sure you do it correctly
.
另一个可能的解决方案是,考虑使用字典将每个方向映射到相反的方向:
opposite = { "NORTH": "SOUTH", "SOUTH": "NORTH", "EAST": "WEST", "WEST": "EAST" }
现在,当您遍历列表时,可以这样做
def consolidate_directions(direction_list):
directions = []
# iterating over enumerate(iterable) is like iterating
# over iterable except it gives you access to both the current
# iteration count and the current item being processed on each iteration
for i, direction in enumerate(direction_list):
# this is a trick to avoid out of bounds error when checking for
# the last element of the list. % is the modulus operator that returns
# 0 if the right hand side divides the left hand side evenly. In this
# case that would signify the first element of the list, meaning the
# current element is the last
last_index = (i - 1) % len(direction_list)
next_index = (i + 1) % len(direction_list)
if next_index == 0:
return directions
else:
if not (direction_list[next_index] == opposite[direction]) \
and not (direction_list[last_index] == opposite[direction]):
directions.append(direction)
return directions
更一般的反馈:大多数Python程序员使用snake case代替camel case作为函数名(如上所述)。而且,作为一种语言,Python的一个好处是它具有高度的可读性——它几乎可以像英语一样阅读。请随意为变量和函数使用高度描述性的名称。这使您的代码对于其他程序员来说更容易阅读和理解,而对于您自己来说,以后更容易阅读和理解。
这是很好地覆盖在
PEP-8 Style Guide
,在用python编程时,您应该尽可能密切地跟踪它。