python列表索引超出范围 等于啥_python列表索引超出范围,即使在分隔索引之后也是如此...

发生错误的原因是您在每次迭代过程中都在迭代列表并删除元素。一般来说,修改您正在迭代的底层对象是危险的,无论您使用什么语言,都会导致有趣的错误。作为一个初学者,这是一个你应该避免的练习,除非你有一个很好的理由去做。

如前所述,创建基础列表的副本并从副本中删除元素,而不是从正在迭代的对象中删除元素,是避免这种情况的好方法。如果你这样做,

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编程时,您应该尽可能密切地跟踪它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值