jim*_*imy 25 python python-3.x
为了找到最常见的,我知道我可以使用这样的东西:
most_common = collections.Counter(array).most_common(to_find)
Run Code Online (Sandbox Code Playgroud)
然而,我似乎无法找到任何可比的,因为找到最不常见的元素.
我可以获得有关如何做的建议.
Joh*_*hin 22
借用collections.Counter.most_common适当的来源和反转:
from operator import itemgetter
import heapq
import collections
def least_common_values(array, to_find=None):
counter = collections.Counter(array)
if to_find is None:
return sorted(counter.items(), key=itemgetter(1), reverse=False)
return heapq.nsmallest(to_find, counter.items(), key=itemgetter(1))
>>> data = [1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4]
>>> least_common_values(data, 2)
[(1, 2), (2, 4)]
>>> least_common_values([1,1,2,3,3])
[(2, 1), (1, 2), (3, 2)]
>>>
Run Code Online (Sandbox Code Playgroud)
Jim*_*som 14
关于什么
least_common = collections.Counter(array).most_common()[-1]
Run Code Online (Sandbox Code Playgroud)
抱歉,这个帖子迟到了...发现文档非常有帮助: https://docs.python.org/3.7/library/collections.html
搜索“最少”,您将看到此表,它有助于获取超过列表中最后一个 (-1) 的元素:
c.most_common()[:-n-1:-1] # n least common elements
Run Code Online (Sandbox Code Playgroud)
这是一个例子:
n = 50
word_freq = Count(words)
least_common = word_freq.most_common()[:-n-1:-1]
Run Code Online (Sandbox Code Playgroud)
只获取最不常见的元素,仅此而已:
>>> from collections import Counter
>>> ls = [1, 2, 3, 3, 2, 5, 1, 6, 6]
>>> Counter(ls).most_common()[-1][0]
5
Run Code Online (Sandbox Code Playgroud)
def least_common_values(array, to_find):
"""
>>> least_common_values([1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4], 2)
[(1, 2), (2, 4)]
"""
counts = collections.Counter(array)
return list(reversed(counts.most_common()[-to_find:]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13531 次 |
| 最近记录: |