Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python - 목록에서 K보다 큰 값의 수

<시간/>

많은 복잡한 문제의 기본 문제 중 하나는 파이썬의 목록에서 특정 숫자보다 큰 숫자를 찾는 것인데 흔히 접하게 됩니다.

예시

# 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