0

In python, if I have

A=[3,3,1,8,2,5,8,2,2]

and I do

set(A)

I get

{1, 2, 3, 5, 8}

i.e. a set with A's elements without duplicates

Is there a fast way to also have counters to know how many instances of every number I have in A?

Something like:

{[1, 1], [2, 3], [3, 2], [5, 1], [8, 2]}

Or do I have to implement it myself?

mugnozzo
  • 210
  • 1
  • 15
  • Use a dictionary where you increment the value each time you add an element. – Barmar Jan 29 '19 at 18:12
  • 9
    [collections.Counter](https://docs.python.org/3/library/collections.html#collections.Counter) – Kevin Jan 29 '19 at 18:13
  • 1
    As @Kevin said, use `collections.Counter`. Something like: `result = collections.Counter(A)`. Then, you can iterate over it using `for value, count in result.items():` to obtain the value and counts respectively. – hqkhan Jan 29 '19 at 18:14
  • This is a clear dupe, but I hope the question is not deleted since people coming from shell scripting/command-line may well ask it exactly in this way, so it could be a useful waypoint – Chris_Rands Jan 29 '19 at 18:17

0 Answers0