0

I have little problem with python's Counter library. Here is an example:

from collections import Counter
list1 = ['x','y','z','x','x','x','y', 'z']
print(Counter(list1))

Output of it:

Counter({'x': 4, 'y': 2, 'z': 2})

My question is how to receive the output without quantity of repetitions?

What I want to get is:

Counter('x', 'y', 'z')
Osho
  • 168
  • 1
  • 9

3 Answers3

1

You need to extract the keys from most_common():

from collections import Counter
list1 = ['x', 'y', 'z', 'x', 'x', 'x', 'y', 'z']

print(Counter(list1).most_common())  # ordered key/value pairs
print(Counter(list1).keys())  # keys not ordered!

keys = [k for k, value in Counter(list1).most_common()]
print(keys)  # keys in sorted order!

Out:

[('x', 4), ('y', 2), ('z', 2)]
['y', 'x', 'z']
['x', 'y', 'z']
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0

If you just want the different elements of a list, you can just convert it into a set.

That being said you can also access the keys of the Counter dictionary using the method keys to obtain a similar result.

Educorreia
  • 375
  • 5
  • 21
0

If we consider the output of Counter as a dictionary, we can get only the strings by getting only the keys of the dictionary:

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
values = Counter(list1).keys()
print(values)
Ismail Hafeez
  • 730
  • 3
  • 10