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。你知道吗
这种简单的方法有效:
输出:
使用列表理解的稍微精细一点的方法,可能不太可读:
输出:
相关问题 更多 >
编程相关推荐