5
example = ['apple', 'pear', 'apple']

How can I get the below from the above

result = [(apple ,2), (pear, 1)]

I only know how to use Counter, but I'm not sure how to turn the results to the format above.

The tuple command would not work:

>>> tuple(Counter(example))
('apple', 'pear')
jpp
  • 159,742
  • 34
  • 281
  • 339
halo09876
  • 2,725
  • 12
  • 51
  • 71

2 Answers2

6

You can call list on Counter.items:

from collections import Counter

result = list(Counter(example).items())

[('apple', 2), ('pear', 1)]

dict.items gives an iterable of key, value pairs. As a subclass of dict, this is true also for Counter. Calling list on the iterable will therefore give you a list of tuples.

The above gives items insertion ordered in Python 3.6+. To order by descending count, use Counter(example).most_common(), which returns a list of tuples.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 3
    Or for sorted results (by count) as a single call, `Counter(example).most_common()` does all the work as a single call. – ShadowRanger Oct 06 '18 at 03:06
1

Just do:

Counter(example).items()

Which is not a list, but if want a list:

list(Counter(example).items())

Because Counter is basically a dict, has equivalent functions to a dict, so Counter has items,

Only thing is that Counter has a elements and most_common (most_common actually can solve this), elements converts Counter to itertools.chain object then make to list will be the original list but ordered by occurrence.

most_common example:

Counter(example).most_common()

No need converting for list, it's already a list, but it orders by number of occurrence (meaning maximum --- to --- minimum).

Both Output:

[('apple', 2), ('pear', 1)]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114