簡體   English   中英

當if語句至少滿足一次時,如何不執行for循環的else語句?

[英]How not to execute else statement of for-loop when if statement is satisfied at least once?

我正在嘗試檢查列表中的所有元素,看看它們是否滿足“小於 5”的條件。 我想要做的是,如果我的列表中沒有數字小於 5,我想打印一條語句“此列表中沒有小於 5 的元素。”,否則只打印那些數字,而不是“此列表中沒有小於 5 的元素。” 還。

list = [100, 2, 1, 3000]
for x in list:
    if int(x) < 5:
        print(x)
else:
    print("There are no elements in this list less than 5.")

這將產生輸出:

2
1
There are no elements in this list less than 5.

我怎樣才能擺脫該輸出的最后一行?

只有在沒有遇到break時才會執行for-loopelse 因此, for-else語句不適用於在列表中查找多個元素,因為第一個break將停止循環。

相反,使用列表理解並根據結果相應地打印。

lst = [100, 2, 1, 3000]

less_than_five = [x for x in lst if x <  5]

if less_than_five:
    print(*less_than_five)
else:
    print('There are no elements in this list greater than 5.')

您可以執行以下操作:

if max(mylist) < 5:
    print('there are no elements in this list greater than 5')
else:
    for x in mylist:
        if int(x) < 5:
            print(x)

這將檢查您的列表是否包含任何大於 5 的內容,如果有,則運行您的循環。

在循環外保留一個布爾標志。 如果至少找到一個元素,則將其設置為 true。 如果標志沒有改變 - 打印出關於沒有發現大於 5 的元素的聲明:

list = [100, 2, 1, 3000]
found = False
for x in list:
  if int(x) < 5:
    print(x)
    found = True

if found == False:
  print("There are no elements in this list greater than 5")     

您需要某種標志來跟蹤是否滿足條件,如下面的代碼所示。 list = [100, 2, 1, 3000] flag = False for x in list: if int(x) < 5: print(x) flag = True if not flag: print("There are no elements in this list greater than 5.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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