-2

For example, if we have a list of a lot of names. How to count occurrences in a sequence? Or more exactly, how to use groupby to sort the list and count? My case, the list is not just ['a','b','c','d']. I have 60 diffenent very long strings.

WJPING
  • 11
  • 5
  • Possible duplicate of [How do I count unique values inside a list](https://stackoverflow.com/questions/12282232/how-do-i-count-unique-values-inside-a-list) – SpghttCd Aug 02 '19 at 09:36

2 Answers2

0

itertools.groupby is a great tool for counting the numbers of occurrences in a sequence.

import itertools
name_test_random = [**a list of a lot of names**]
valdict = dict((k, len(list(g)))
           for k, g in itertools.groupby(name_test_random))
for key, val in valdict.items():
    print(key, ":", val)
WJPING
  • 11
  • 5
0

use Counter from collections:

l = np.random.choice(list('asdf'), 10)
# array(['f', 's', 's', 'a', 'f', 'a', 'a', 'd', 'd', 'd'], dtype='<U1')

from collections import Counter

Counter(l)
# Counter({'f': 2, 's': 2, 'a': 3, 'd': 3})
SpghttCd
  • 10,510
  • 2
  • 20
  • 25