[英]Can I stop the for loop from continuing on the last index of the array I am iterating over?
我在 Hackerrank 上为“堆积挑战”编写了一个代码,它应该遍历一个列表并检查列表中的元素是否按降序排列。
for i in range(1, len(l)):
if l[i - 1] < l[i]:
print('No')
break
else:
print('Yes')
continue
但是,使用 else 语句,如果列表按降序正确排序,它将在循环中的每次迭代中重复打印“是”。 如果所有元素都满足条件,是否可以在循环的最后一次迭代中只打印一个“是”? 谢谢!!!
这是对不太知名的for: else:
构造的一个很好的使用:
for i in range(1, len(l)):
if l[i - 1] < l[i]:
print('No')
break
else:
print('Yes')
else:
与for:
: 配对仅在循环成功完成时执行。 有关更多详细信息, 请参阅文档。
假设所有元素都已排序。 然后试着找一个例子来废除这个论点。
您可以使用定义排序顺序的变量,然后通过循环分配正确的值。 这样就不需要每次都记录“是”。
sorted_order = True
for i in range(1, len(l)):
if l[i - 1] < l[i]:
print('index '+ (i-1) +' and '+ i +' are in incorrect order')
sorted_order = False
break
if sorted_order:
print('true')
else
print('false')
可以在for
循环之后使用else
,如果循环没有被break
语句跳出来,就会在循环之后执行:
for i in range(1, len(l)):
if l[i - 1] < l[i]:
print('No')
break
else:
print('Yes')
但有些人可能不喜欢这种方式。 我更喜欢使用any
:
if any(l[i - 1] < l[i] for i in range(1, len(l))):
print('No')
else:
print('Yes')
与pairwise
合作(在Python3.10中)更Pythonic:
from itertools import pairwise
if any(i < j for i, j in pairwise(l)):
print('No')
else:
print('Yes')
更快的方式:
from operator import lt
from itertools import starmap, pairwise
if any(starmap(lt, pairwise(l))):
print('No')
else:
print('Yes')
我就是这样做的。 通过拥有一个函数,您可以使用多个数据。 这段代码也快了至少 50%。
def is_sorted_better(x):
# If a single item is larger than the last item, then you return 'no'
if any(x[i - 1] < x[i] for i in range(1, len(x))):
# You can add any extra lines for if it isn't in order here
return 'no'
# if all items have been checked and there are no issues, return yes
# You can place additional code here like 'sorted_order = True'
return 'yes'
这里没有注释的代码:
def is_sorted_better(x):
if any(x[i - 1] < x[i] for i in range(1, len(x))):
return 'no'
return 'yes'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.