List comprehension with conditional

Asked

Viewed 789 times

1

My goal is to count how many elements of a given list correspond to a condition. To do so, 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 fix this?

  • 3

    You can read my answer about how to filter a Python list for more information. Obviously if the intention is only to count the amount of elements equal to the max, the more pythonic is seq.count(max) as commented in the replies.

  • Take a look at this link

5 answers

5

5

To count the elements of a list that satisfy a certain condition, taking into account the question title ("list understanding") 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, ==) enough and advise to do:

cont = seq.count(max)

DEMONSTRATION

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

  • Given that the focus of AP is problem resolution (using understandings) and not necessarily the error message, I would say that this is the best answer and should be the accepted. :)

  • 1

    @Luizvieira hello, I think. I had just added the answer about the error, it was right in the timing. Obgado (I deleted the previous comment because I forgot to reply directly to what I said)

  • 1

    For nothing. Anyway, who really defines which is the best and should be accepted is Vinicius, right? I was just giving my opinion.

2


Hello. The syntax used by you in your code is incorrect based on the patterns of the language, and Python, a block is always delimited by two points ':' followed by a:

line break with 4-space tab already predefined by the IDE (which may be modified in accordance with the user preference),

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 preview option, so the user could choose between viewing how many values are between the conformities or leaving the program.

  • Felix has a few points on the less correct answer. Regarding the tab, nothing says that it needs to be 4 spaces, it can be up to only one space, eg: http://ideone.com/OX7Wt9 as long as you keep the same throughout the program. Nor do you have the "obligation" to change lines (but by convention, yes, we did, and in some cases it would be wrong if you did not), but here is the program of my reply in one line: http://ideone.com/idB5wF

  • @Miguel - Yes, I agree about the tabulation, but by convention we have adopted the tabulation of 4 spaces as default, this is already included in the Ides. About your program on a single line, you used other parameters to perform this feat, but for beginners the basic is the simple, so I quoted this.

  • yes, what you said is the convention but in the answer you seem to mean it’s the rule, I made a repair so that you could edit if you wanted, not to mislead others

  • @Miguel - Understood then, I will take this tip for the next answers, not to confuse the other XD

  • HI - your syntax is incorrect, with an indentation "from scratch" in the second line.

  • Your return is also incorrect: Pyhton does not require the indentation to be "4 spaces" - there only needs to be an indentation, which can be any number of spaces and/or. By style convection you use 4 spaces - but your text puts as if this is part of the syntax.

  • @jsbueno - Thank you, it was time to add the pre-code, I added an extra note, thanks for the XD warning, I’m still getting used to the Stack system

  • @jsbueno - On 4-space tabulation, that’s what I quoted to Miguel, by convention, we accept 4-blank tabulation with a certain ease, and with that, most text editors already come with this property as Default, in simple terms, talking about the 4-space tab can be referred to this reason, not that it is mandatory, but it is the most used and comes by default in the IDE, and with this can be easily modified by the user.

  • @Andersoncarloswoss - Is corrected

  • What jsbueno means is that you can make it clear already in the answer that there is no obligation to be 4 spaces, that it is mandatory to have only indentation, but that 4 spaces are used according to the PEP 8 (Citing PEP would also be interesting).

  • @Andersoncarloswoss- Sure, in the future I will take these precautions

Show 6 more comments

0

From what I understand you want to implement a list comprehension in which you can count the number of times the value "10" I repeated in that list.

Well, to resolve this issue we can use the following code:

print(len([x for x in list(map(int, input('Digite os valores: ').split())) if x == 10]))

Note that when we execute the code we receive the following message: Digite os valores: . Right now we must type all the values, in the same line, separated for a single space and press enter.

From that moment the values captured by input() will be stored in a list. Next the block for shall cover all the elements of that list and with the help of the if check whether the value of x is equal to 10. If yes, the value will be stored in the list. Then the function len() calculate the size of this list and display the amount of values 10.

0

As colleagues have already said, the two points are missing : after for x in seq and if x == max and python does not allow certain constructs to be positioned on the same line:

cont = 0
seq = [1, 2, 3, 6, 10, 77, 92, 10, 10]
max = 10
for x in seq:
  if x == max:
    cont = cont+1

print(cont)  

I would like to suggest another approach, functional programming using the module functools that offers functions that act on or return other functions.

In case the solution uses the function reduce() which bears the following signature:

functools.reduce( função , iterável [ , inicializador ] )

Applies to função of two arguments cumulatively to the items of the eternal left to right, so as to reduce the iterable to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
The left argument, x, is the accumulator and the right argument, y, is a value from the eternal.
If the optional initializer is present, it is placed before the iterable items in the calculation and serves as the default when the iterable is empty.
If the initializer is not provided and the iterable contains only one item, the first item will be returned.

In the example was used a lambda function comparing an element e of seq with max. If both are equal sum 1 to the accumulator a or just give it back a:

from functools import reduce

seq = [1, 2, 3, 6, 10, 77, 92, 10, 10]
max = 10

cont = reduce(lambda a, v : a + (1 if v==max else 0), seq, 0)

print(cont)   #3

Test the code on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.