【问题标题】:(Python) Function to check if a element is the same as the next, returns IndexError when examining the last element(Python) 检查一个元素是否与下一个元素相同的函数,检查最后一个元素时返回 IndexError
【发布时间】:2020-07-27 08:44:38
【问题描述】:

我正在尝试在 Python 中编写一段代码,以检查数字中的元素是否与下一个元素相同。 问题是,当 if 语句检查最后一个元素时,它无法检查它是否与下一个相同,因为没有下一个元素。

我的代码:

 for i, elem in enumerate(number):
    if elem == number[i + 1]:
        count = count + 1
    else:
        break

new_num = count + elem + index

这会返回

if elem == number[i + 1]:
IndexError: index out of range

使用 while 循环更好,还是可以用 try 和 except 语句来修复?我都试过了,但不确定我是否正确使用。

【问题讨论】:

  • 我的建议是从第二个对象开始并与前一个对象进行比较(如果第二个对象不存在数据为空或只有一个元素)这解决了“最后一个元素”问题
  • 或迭代直到最后一个元素。

标签: python for-loop if-statement enumerate index-error


【解决方案1】:
for i, elem in enumerate(number):
    if i==0:
     continue; # skip the first element
    if elem == number[i - 1]: # is the element same as previous?
        count = count + 1
    else:
        break

new_num = count + elem + index

【讨论】:

  • 否,因为第一个元素是在 i=1 上的迭代中读取的,通过切片去除它会导致“原始”数字 [0] 永远不会被评估。
  • 对,对。 掌心
【解决方案2】:

由于您正在使用索引,因此您可以使用 range() 并且不要一直使用。我的意思是:

for i in enumerate(len(number) - 1):
    if elem == number[i + 1]:
        count = count + 1
    else:
        break

此外,使用 break 语句被认为是不好的做法,最好将其用作 while 循环的条件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2016-06-02
    相关资源
    最近更新 更多