How to find numbers greater than X in a list

0

As an example, this code there

N=[1,2,3,4,5]
B= #quantidade de números maiores que 2
print(B)

'B' would be the number of numbers greater than 2 in the list, for example.

    
asked by anonymous 23.09.2017 / 03:02

3 answers

3

For simplicity you can use this way:

minha_lista = [1,2,3,4,5]
maior_que = 2

filtrados = [x for x in minha_lista if x > maior_que]

#exibe os elementos
print(filtrados)

#conta os elementos
print(len(filtrados))
    
23.09.2017 / 03:20
3

The logic is exactly the same for filtering elements of a list:

Filter elements of a list in Python

The simplest and most direct way is to use list comprehension:

B = len([i for i in N if i > 2])

In this case, we use the len function to calculate the number of elements.

  

See working at Ideone .

Another way, equivalent to list understanding, is to use the filter function:

B = filter(lambda i: i > 2, N)

However, the return of this function will be a generator, thus requiring the conversion to list to get its length:

B = len(list(filter(lambda i: i > 2, N)))

But for this solution, this method becomes impractical compared to the first one.

  

See working at Ideone .

    
23.09.2017 / 03:21
0

Here a solution, there may be easier and smaller

lista = [1,2,3,4,5,6,7,8,9,1,23]
X = 0
B = 0 # Armazena a quantidade de números maiores que 2
num_elementos_lista = len(lista)
while(X < num_elementos_lista):
    if lista[X] > 2: # verifica se lista[X] é maior que 2
      B+=1 # Se for incrementa + 1 em B
    X+=1

print(B)

See working at repl

    
23.09.2017 / 03:18