Listening with conditional list

1

My goal is to count how many elements of a given list correspond to a condition. For that, I made the following lines of code:

cont = 0
seq = []
max = 10
for x in seq if x == max:
    cont = cont+1

However, I get syntax error in if x == max . How can I resolve this?

    
asked by anonymous 18.03.2017 / 14:06

3 answers

2

Hello. The syntax used by the master in his code is incorrect based on the language patterns, and Python, a block is always delimited by two '': colon followed by a:

  

user preference tab wrapping with 4 pre-defined spaces in the IDE

The most accessible syntax based on your question would be as follows.

cont = 0
seq = [0 , 5, 6, 7, 8, 9, 6, 10, 10, 25]
max = 10
for x in seq:
    if x == max:
        cont = cont+1

op = int(input("DESEJA VERIFICAR O RESULTADO? DIGITE 1 PARA VISUALIZAR OU OUTRO VALOR PARA SAIR " ))
if op == 1:
    print("FORAM ENCONTRADOS %i valores" %(cont))
else:
    print()

Note that I modified the original program and applied the display option, so the user could choose to see how many values are between the conformities or exit the program.

    
18.03.2017 / 16:06
4

if can not be on the same line as for .

cont = 0
seq = []
max = 10
for x in seq:
    if x == max:
        cont = cont + 1
print(cont)

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
18.03.2017 / 14:23
4

To count the elements of a list that satisfy a given condition, given the title of the question ("list comprehension") you can do:

seq = [1,3,4,21,10,30,10,24]
max = 10
cont = len([x for x in seq if x == max]) # 2

Note that for this specific purpose (since the condition is equality, == ) suffice and I advise you to do:

cont = seq.count(max)

DEMONSTRATION

PS: This occurs because you have if on the same line as for , not correct syntax for a list comprehension

    
18.03.2017 / 14:35