繁体   English   中英

按使用量的顺序对变量的字符进行排序(PYTHON)

[英]Sort the characters of a variable in order of amount of use (PYTHON)

例:

输入数据进行排序:“ Hello World”排序:[“ l”,3,“ o”,2,“”,1,“ H”,1,“ W”,1,“ d”,1,“ e” ,1,“ r”,1]按ASCII顺序所以我希望它按照出现的次数与出现字符的次数进入表中。

#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]

使用Counter

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

如果您希望结构完全像您所说的那样,

排序:[“ 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]

不过,我不建议您这样做,因为这样做会使此操作更加混乱。

import collections
letters = collections.Counter(uncompressedInput)
print(letters)
from collections import Counter
[e for x in sorted(Counter("hello world").items(), key=lambda t: t[1], reverse=True) for e in x]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM