Python程式檢查列表中所有值是否大於給定值


在本教程中,我們將檢查列表中的所有元素是否都大於某個數字。例如,我們有一個列表 [1, 2, 3, 4, 5] 和一個數字 0。如果列表中的每個值都大於給定值,則返回True 否則返回False

這是一個簡單的程式。我們可以在不到 3 分鐘的時間內編寫它。請先自己嘗試一下。如果你無法找到解決方案,那麼請按照以下步驟編寫程式。

  • 初始化一個列表和任何數字
  • 迴圈遍歷列表。
If yes, return **False**
  • 返回 True。

示例

## initializing the list
   values = [1, 2, 3, 4, 5]
## number num = 0
   num_one = 1
## function to check whether all the values of the list are greater than num or not
   def check(values, num):
   ## loop
      for value in values:
         ## if value less than num returns False
         if value <= num:
            return False
   ## if the following statement executes i.e., list contains values which are greater than given num
   return True
   print(check(values, num))
   print(check(values, num_one))

如果你執行以上程式,

輸出

True False

另一種查詢方法是使用all()內建方法。all()方法如果可迭代物件中的每個元素都為True,則返回 True,否則返回False。讓我們看看使用all() 方法的程式。

## initializing the list
values = [1, 2, 3, 4, 5]
## number
num = 0
num_one = 1
## function to check whether all the values of the list are greater than num or not def check(values, num):
   ## all() method
   if all(value > num for value in values):
      return True
   else:
      return False
print(check(values, num))
print(check(values, num_one))

如果你執行以上程式,

輸出

True 
False

如果您對程式有任何疑問,請在評論區提出。

更新於: 2019年8月27日

798 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.