0

Example:

Enter data to sort: "Hello World" Sorted: ["l", 3, "o", 2, " ", 1, "H", 1, "W", 1, "d", 1, "e", 1, "r", 1] In ASCII order So I want it to go into a table in order of the amount of times it comes up with the amount of times that character comes up.

#Like this
uncompressedInput = input("Enter data to compress: ")
# user inputted "abc"
print("Analysing...")
#sorted = str.sort(uncompressedInput)
#print(sorted)
# ["a", 1, "b", 1, "c", 1]
  • 3
    Duplicate of https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python – John Gordon Oct 18 '17 at 14:26
  • 1
    Possible duplicate of [How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) – Chris_Rands Oct 18 '17 at 14:26

3 Answers3

1

Use Counter

>>> import collections
>>> collections.Counter(uncompressedInput).most_common()
=> [('l', 3), ('o', 2), ('H', 1), ('e', 1), (' ', 1), ('W', 1), ('r', 1), ('d', 1)]

If you want the structure exactly like as you said,

Sorted: ["l", 3, "o", 2, " ", 1, "H", 1, "W", 1, "d", 1, "e", 1, "r", 1]

>>> l = []
>>> [ l.extend([key,val]) for key,val in collections.Counter(s).most_common() ]
>>> l
=> ['l', 3, 'o', 2, 'H', 1, 'e', 1, ' ', 1, 'W', 1, 'r', 1, 'd', 1]

Though, I would not recommend doing that since it will make further computation on this more confusing.

Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
0
import collections
letters = collections.Counter(uncompressedInput)
print(letters)
0
from collections import Counter
[e for x in sorted(Counter("hello world").items(), key=lambda t: t[1], reverse=True) for e in x]
BallpointBen
  • 9,406
  • 1
  • 32
  • 62
  • Check `collections.Counter.most_common()`: https://docs.python.org/3.6/library/collections.html#collections.Counter.most_common – Adirio Oct 18 '17 at 14:38
  • 1
    Code-only answers are discouraged. Can you say something as to why this works as desired? – lit Oct 18 '17 at 15:07