我正在检查列表的连续索引,并且我想执行相同的代码,以防连续元素不相等或列表索引超出范围。 这就是我正在尝试的
for n in range(len(myList))
try:
if myList[n]==myList[n+1]:
#some code
else:
#if they are not equal then do something
#same code should execute if exception raised: index error --> how do i do this?
有没有一种方法可以优雅地做到这一点,而不必以某种方式在 except block 中重复相同的代码?
最佳答案
执行此操作的一种简单方法是仅修改 if 语句以检查候选元素是否不是最后一个,从而避免需要异常子句并保持代码简短。
for n, i in enumerate(myList):
if n+1 != len(myList) and i == myList[n+1]:
#some code
else:
#if they are not equal then do something
#This block will also be exicuted when last element is reached
关于python - 如何在 try block 中的条件执行相同的代码而不在 except 子句中重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559765/