[英]How to make a loop run up to when it stops making sense?
I have a loop inside a program which should be 我在程序中有一个循环
while number >= lst[count]:
rank -= 1
count += 1
where I would like the while to run until it stops making sense. 我想要一段时间才能运行,直到不再有意义为止。 I've attempted somethings which have not worked (see the end of the post), but the following has worked:
我尝试了一些无效的方法(请参阅文章末尾),但是以下方法有效:
lst = [int(x) for x in input().split()]
number = int(input())
count = 0
rank = 0
def attempt(lst, a):
try:
result = lst[a]
except:
result = float('inf')
return result
while number >= attempt(lst, count):
rank -= 1
count += 1
print(rank)
However, I don't think this is very elegant and seems contrived. 但是,我认为这不是很优雅并且似乎是人为的。 Is there a more elegant solution (for this case, and also in general for a given condition)?
是否有更优雅的解决方案(在这种情况下,以及通常在给定条件下)?
Other attempts (which were unsuccessful): 其他尝试(不成功):
while aliceScores[i] >= lst[count] and count < len(lst):
rank -= 1
count += 1
The above fails because the while tries to run for count = len(lst) and runs an error, since lst[len(lst)] does not exist. 上面的操作失败,因为while尝试运行count = len(lst)并运行错误,因为lst [len(lst)]不存在。
while aliceScores[i] >= lst[count] and count < len(lst)-1:
rank -= 1
count += 1
The above fails because I want to modify the rank if the condition happens also in the case lst[len(lst) - 1], which would not be seem in the above code. 上面的方法失败了,因为在lst [len(lst)-1]的情况下,如果条件也发生了,我想修改等级,这在上面的代码中不会出现。
The only reason why 唯一的原因
while aliceScores[i] >= lst[count] and count < len(lst):
rank -= 1
count += 1
does not work is that you cannot evaluate lst[count] when count is too big, however you can exploit the fact python short-circuits and/or operators 不起作用是,当count太大时,您无法评估lst [count],但是您可以利用python 短路和/或运算符这一事实
while count < len(lst) and aliceScores[i] >= lst[count]:
rank -= 1
count += 1
This way the loop will stop properly either if count is too big, or if the second condition becomes False. 这样,如果计数太大或第二个条件为False,则循环将正确停止。
Why not use a for
to iterate the list, and an enumerate
to count the number of tries. 为什么不使用
for
来迭代列表,并使用enumerate
来计数尝试次数。 It would be more pythonic than a while
imho. 它比
while
恕我直言更具Python性。
def get_rank(...):
for index, lst_number in enumerate(lst):
if number < lst_attempt:
return -index
return -len(lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.