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
热门推荐
6 祝福语简短七夕
10 白羊生日祝福语 简短独特
11 送花简短有内涵祝福语
12 老师节祝福语的简短
13 孩子满月随礼简短祝福语
14 对别人新年祝福语简短
15 甄嬛传祝福语简短
16 企业励志拜年祝福语简短
17 高考已上岸祝福语简短
18 新年发给客户祝福语简短