簡體   English   中英

如何使循環運行到停止有意義為止?

[英]How to make a loop run up to when it stops making sense?

我在程序中有一個循環

while number >= lst[count]:
    rank -= 1
    count += 1

我想要一段時間才能運行,直到不再有意義為止。 我嘗試了一些無效的方法(請參閱文章末尾),但是以下方法有效:

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)

但是,我認為這不是很優雅並且似乎是人為的。 是否有更優雅的解決方案(在這種情況下,以及通常在給定條件下)?


其他嘗試(不成功):

while aliceScores[i] >= lst[count] and count < len(lst):
    rank -= 1
    count += 1

上面的操作失敗,因為while嘗試運行count = len(lst)並運行錯誤,因為lst [len(lst)]不存在。

while aliceScores[i] >= lst[count] and count < len(lst)-1:
    rank -= 1
    count += 1

上面的方法失敗了,因為在lst [len(lst)-1]的情況下,如果條件也發生了,我想修改等級,這在上面的代碼中不會出現。

唯一的原因

while aliceScores[i] >= lst[count] and count < len(lst):
    rank -= 1
    count += 1

不起作用是,當count太大時,您無法評估lst [count],但是您可以利用python 短路和/或運算符這一事實

while count < len(lst) and aliceScores[i] >= lst[count]:
    rank -= 1
    count += 1

這樣,如果計數太大或第二個條件為False,則循環將正確停止。

為什么不使用for來迭代列表,並使用enumerate來計數嘗試次數。 它比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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM