python - 如何检查列表中的所有整数是否连续?

标签 python python-3.x for-loop enumerate

我正在尝试编写一个程序,如果 list 中的所有数字都是连续的,它将打印“YES”,如果数字不连续,则应返回“NO”。连续的意思是列表中的每个数字都应该大于前一个元素中的数字。

例如:

  • 它应该为输入打印“YES”:[3, 4, 5], [7, 8, 9], [1 , 2, 3], [0, 1, 2, 3, 4, 5].. 等

  • 它应该为输入打印“NO”:[9, 1, 0], [3, 2, 4], [5 , 5], [9, 8, 2, 3, 7].. 等

为此我使用了 enumerate

这是我的代码:

    inp=[1,2,3,4,5]
    flag=0
    for index,e in enumerate(inp): 
        if index!=len(inp)-1:    
            if inp[index+1]==inp[index]+1:
                flag=1
    if flag==1:
        print ("YES")
    else:
        print ("NO")

代码工作正常,但我发现它是多余的。
使用枚举或不使用枚举是否有更好的方法?

最佳答案

您不需要enumerate 来检查列表的元素是否连续。您可以通过使用 zip 创建一个函数来简单地实现它和 all作为:

def check_continuity(my_list):
    return all(a+1==b for a, b in zip(my_list, my_list[1:]))

通过 any 可以获得相同的结果与 zip as (类似于 all,但有 not!= 用于比较):

def check_continuity(my_list):
    return not any(a+1!=b for a, b in zip(my_list, my_list[1:]))

以上函数将返回 True/False,具体取决于您的列表是否连续。

样本运行:

# Continuous Lists
>>> check_continuity([3, 4, 5])
True
>>> check_continuity([7, 8, 9])
True
>>> check_continuity([1, 2, 3])
True

# Non Continuous Lists
>>> check_continuity([9, 1, 0])
False
>>> check_continuity([3, 2, 4])
False
>>> check_continuity([5, 5])
False

为了打印“YES”/“NO”,您可以在函数调用外部做一个简单的if..else检查:

>>> "YES" if check_continuity([1, 2, 3]) else "NO"
'YES'

# OR update the return statement in your function to
#    return "NO" if any(a+1!=b for a, b in zip(my_list, my_list[1:])) else "YES"

关于python - 如何检查列表中的所有整数是否连续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596542/

相关文章:

python-3.x - django.core.exceptions.ImproperlyConfigured : WSGI application 'wsgi.application' could not be loaded; Error importing module

java - Java 中的 ListIterator 分配

python - 如何使用 python 包分发数据文件以使其可读?

python - 使用鼠标移动 QtWidgets.QtWidget

python - 如果这些字符串略有不同,如何根据另一个列表中的字符串从列表中删除某些字符串?更多信息如下

c++ - for循环的简写——C++中的语法糖(11)

r - 使用 foreach 循环和并行处理生成矩阵

python - Ubuntu 在使用 Firefox 的系统启动时运行 python 脚本

Python paho mqtt客户端不会同时发布和订阅

python - 将 10 位无符号整数转换为 python 中的有符号整数