计数器。最常见有点误导

2024-04-26 15:00:21 发布

您现在位置:Python中文网/ 问答频道 /正文

min_number_of_tops = 3
c = Counter(['x','b','c','d','e','x','b','c','d','x','b'])
print(c.most_common(min_number_of_tops))

输出:

[('b', 3), ('x', 3), ('c', 2)] 

或:

[('b', 3), ('x', 3), ('d', 2)] 

但我更希望most_common返回这样的内容:

[('b', 3), ('x', 3), ('d', 2), ('c', 2)]

因为我对包含给定计数的所有元素感兴趣。你知道吗

无论如何,我需要生成一个表示顶级结果的排序列表,但也要返回与第3项计数相同的任何其他项。例如:

['x', 'b', 'c', 'd']

以下是我制作此列表的尝试:

def elements_above_cutoff(elem_value_pairs, cutoff):
    ''' presuming that the pairs are sorted from highest value to lowest '''
    for e,v in elem_value_pairs:
        if v >= cutoff:
            yield e
        else:
            return

min_number_of_tops = 3
c = Counter(['x','b','c','d','e','x','b','c','d','x','b'])
print(list(elements_above_cutoff(c.most_common(),c.most_common(min_number_of_tops)[-1][1])))

它给出:

['b', 'x', 'd', 'c']

你能建议一个更好的方法吗?我在用Python3。你知道吗


Tags: ofnumbermost列表valuecounterelementscommon
1条回答
网友
1楼 · 发布于 2024-04-26 15:00:21

这种简单的方法有效:

import collections
common = collections.Counter(['x','b','c','d','e','x','b','c','d','x','b']).most_common()
min_number_of_tops = 3
if len(common)>min_number_of_tops:
    freq = common[min_number_of_tops-1][1]
    for i in range(min_number_of_tops, len(common)):
        if common[i][1] < freq:
            common = common[:i]
            break
print(common)   

输出:

[('b', 3), ('x', 3), ('d', 2), ('c', 2)]

使用列表理解的稍微精细一点的方法,可能不太可读:

import collections
common = collections.Counter(['x','b','c','d','e','x','b','c','d','x','b']).most_common()
min_number_of_tops = 3
testfreq = common[min_number_of_tops-1][1] if len(common)>min_number_of_tops else 0
common = [x for x, freq in common if freq >= testfreq]
print(common) 

输出:

['b', 'x', 'd', 'c']

相关问题 更多 >