我正在尝试编写一个程序,如果 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/