Python - 列表中大於 K 的值的數量


解決許多複雜問題的一個基本問題是,在 Python 中從列表中找出大於某個數字的數字。

示例

 線上演示

# find number of elements > k using for loop
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using for loop to get numbers > k
count = 0
for i in test_list :
   if i > k :
      count = count + 1
# printing the intersection
print ("The numbers greater than 4 : " + str(count))    
# find number of elements > k using list comprehension
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using list comprehension to get numbers > k
count = len([i for i in test_list if i > k])
# printing the intersection
print ("The numbers greater than 4 : " + str(count))
# find number of elements > k using sum()
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
# initializing k
k = 4
# printing list
print ("The list : " + str(test_list))
# using sum() to get numbers > k
count = sum(i > k for i in test_list)
# printing the intersection
print ("The numbers greater than 4 : " + str(count))

輸出

The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4
The list : [1, 7, 5, 6, 3, 8]
The numbers greater than 4 : 4

更新於:06-Aug-2020

679 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.