Python Collection Counter.most_common(n)方法返回前n个元素及其计数。但是,如果两个元素的计数相同,如何返回按字母顺序排序的结果?
例如:对于像这样的字符串BBBAAACCD,对于“最常见的2个”元素,我希望结果是指定的n = 2:
[('A', 3), ('B', 3), ('C', 2)]
Run Code Online (Sandbox Code Playgroud)
并不是:
[('B', 3), ('A', 3), ('C', 2)]
Run Code Online (Sandbox Code Playgroud)
请注意,虽然A与B具有相同的频率,A来之前B,因为它到来之前在结果列表中B按字母顺序排列。
[('A', 3), ('B', 3), ('C', 2)]
Run Code Online (Sandbox Code Playgroud)
我该如何实现?
给定一个字符串:
this is a test this is
Run Code Online (Sandbox Code Playgroud)
我怎样才能找到最常见的2克?在上面的字符串中,所有2克都是:
{this is, is a, test this, this is}
Run Code Online (Sandbox Code Playgroud)
你可以注意到,2克this is出现了2次.因此结果应该是:
{this is: 2}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用Counter.most_common()方法来查找最常见的元素,但是如何从字符串开始创建一个2-gram的列表呢?