Keg*_*sRo 2 python for-loop enumerate python-3.x
我正在尝试编写一个程序,如果其中的所有数字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")
Run Code Online (Sandbox Code Playgroud)
该代码工作正常,但我发现它是多余的。
有没有更好的方法来使用枚举或不使用枚举?
您不需要enumerate检查列表的元素是否连续。zip您可以通过使用and创建一个函数来简单地实现它all:
def check_continuity(my_list):
return all(a+1==b for a, b in zip(my_list, my_list[1:]))
Run Code Online (Sandbox Code Playgroud)
any通过with zipas可以获得相同的结果(类似于allbut withnot和!=for 比较):
def check_continuity(my_list):
return not any(a+1!=b for a, b in zip(my_list, my_list[1:]))
Run Code Online (Sandbox Code Playgroud)
上述函数将返回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
Run Code Online (Sandbox Code Playgroud)
为了打印“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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3440 次 |
| 最近记录: |