0

I have list:

s = list(map(int, ['0', '0', '2', '1', '1', '0', '0', '0']))

I need to figure out how to take a nonzero number from the list that has more concurrence (in this example it is '1'). If concurrence of numbers is the same (e.g. ['0', '2', '2', '1', '1', '0', '0']) take first nonzero number in the list (in this example it is '2'). If the list consists of zeros than return zero.

It seems that

max(set(s), key=s.count)

can help but it has problems with zeros. For the example above it returns 0.

illuminato
  • 1,057
  • 1
  • 11
  • 33
  • 3
    Look into [`collections.Counter`](https://docs.python.org/3/library/collections.html?highlight=collections%20counter#collections.Counter) – r.ook Apr 07 '20 at 15:47

2 Answers2

2

you can use collections.Counter:

from collections import Counter
s =  ['0', '0', '2', '1', '1', '0', '0', '0']

try:
    print(next(t[0] for t in Counter(s).most_common(2) if t[0] != '0'))
except StopIteration:
    print('0')

output:

1

Counter.most_common :

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered

kederrac
  • 16,819
  • 6
  • 32
  • 55
0

Counter registers values in order, so it does exactly what you're looking for:

from collections import Counter
l = list(map(int, ['0', '0', '1', '1', '2', '2', '0', '0']))
c = Counter(l)
del c[0]
c.most_common(1)[0][0]

Output:

1

If I change the list so there's more 2 first, the output will change:

l = list(map(int, ['0', '0', '2', '1', '2', '1', '0', '0']))
c = Counter(l)
del c[0]
c.most_common(1)[0][0]

Output:

2
Juan C
  • 5,846
  • 2
  • 17
  • 51