Python | Número de valores mayores que K en la lista

Uno de los problemas que es básicamente un subproblema para muchos problemas complejos, encontrar números mayores que cierto número en la lista en python, se encuentra comúnmente y este artículo en particular analiza las posibles soluciones a este problema en particular.

Método 1: método ingenuo
La forma más común de resolver este problema es usando bucle y simplemente contando las ocurrencias de elementos que son mayores que el número K dado.

# Python 3 code to demonstrate 
# find number of elements > k
# using naive method 
  
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
  
# initializing k
k = 4
  
# printing list 
print ("The list : " + str(test_list))
  
# using naive method 
# 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))

Producción :

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

Método 2: Uso de la comprensión de listas
Este método logra esta tarea de manera similar, pero de una manera más concisa. La comprensión de listas siempre reduce las líneas de códigos en el programa aunque ejecuta un enfoque similar en segundo plano.

# Python 3 code to demonstrate 
# 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))

Producción :

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

Método 3: Usarsum()
The sum()también puede ayudarnos a lograr esta tarea. Podemos devolver 1 cuando se encuentra el número mayor que k y luego calcular la suma de está usandosum()

# Python 3 code to demonstrate 
# 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))

Producción :

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

Método 4: usandofunctools.reduce()
Usando reduce(), también podemos realizar la suma de todos los números recolectados para la función y luego acumularlos para devolver el resultado, es decir, el conteo de números mayores que K.

# Python 3 code to demonstrate 
# find number of elements > k
# using reduce()
from functools import reduce
  
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
  
# initializing k
k = 4
  
# printing list 
print ("The list : " + str(test_list))
  
# using reduce()
# to get numbers > k
count = reduce(lambda sum, j: sum  + (1 if j > k else 0), test_list, 0)
  
# printing the intersection 
print ("The numbers greater than 4 : " + str(count))

Producción :

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

Método 5: el usobisect() + sort()
de la combinación de sort()y bisect()puede realizar la tarea de búsqueda binaria y, por lo tanto, obtener el índice y restar el tamaño de la lista puede ayudarnos a obtener elementos que son más grandes que un elemento particular en la lista.

# Python 3 code to demonstrate 
# find number of elements > k
# using bisect() + sort()
from bisect import bisect
  
# initializing list
test_list = [1, 7, 5, 6, 3, 8]
  
# initializing k
k = 4
  
# printing list 
print ("The list : " + str(test_list))
  
# using bisect() + sort()
# to get numbers > k
test_list.sort()
count = len(test_list) - bisect(test_list, k)
  
# printing the intersection 
print ("The numbers greater than 4 : " + str(count))

Producción :

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

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *