List counting elements

Asked

Viewed 66 times

-2

I have a list, like this:

L = [0, 0, 1, 1, 1]

If you used the command SET:

L = [0,1]
sum(L) = 2

The answer I need would be: 3. Each pair of answers would be one point, as it has two '0' = 1, one point, three '1' = 2

OBS: Sorry but I formulated the question incompletely so I revised

  • 3

    If you just sum(L) as a list will output 3. What is the purpose of using set? And how did you get the result 2 with sum? By the way, do you need to count the number of elements or add them up? Text says one thing, code says another.

  • "The answer I need would be: 3" And this 3 is the most concrete ?

  • I’m trying to understand your doubt, improve the text and maybe I can help you.

2 answers

1


To add up the contents of a sequence, just use the sum. If you want to add up all the numbers in the list, you should not, of course, reduce it to a set using set.

Already, to count the number of occurrences of each element in a sequence (such as a list) or an iterable (such as lines an open file), you can use Collections. Counter - which automatically groups occurrences into an object that can be read as if it were a dictionary:

In [3]: from collections import Counter

In [4]: L = [0, 0, 1, 1, 1]

In [5]: Counter(L)
Out[5]: Counter({0: 2, 1: 3})

In [6]: Counter(L)[1]
Out[6]: 3

Check out the Counter documentation on: https://docs.python.org/3/library/collections.html#Collections. Counter

  • Thank you, you answered what I needed

0

set() does not allow repeated values. If you want to add 3 times the same value (1) you should use list(), not set().

>>> lista = [0, 0, 1, 1, 1]
>>> print(sum(lista)) 
3

Browser other questions tagged

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