List counting elements [closed]

-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 response pair would be a point, as it has two '0' = 1, one point, three '1' = 2

NOTE: I'm sorry but I did not complete the question so I reviewed

    
asked by anonymous 12.09.2018 / 14:22

2 answers

1

To sum the content of a sequence, just use sum . If you want to add 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 (like the rows an open file), you can use collections.Counter - which automatically groups the 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 at: link

    
12.09.2018 / 15:01
0

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

>>> lista = [0, 0, 1, 1, 1]
>>> print(sum(lista)) 
3
    
12.09.2018 / 14:44