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?

4
  • Use a dictionary where you increment the value each time you add an element. Commented Jan 29, 2019 at 18:12
  • 9
    collections.Counter Commented Jan 29, 2019 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. Commented Jan 29, 2019 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 Commented Jan 29, 2019 at 18:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.