2011-01-20 30 views
16

Để tìm phổ biến nhất, tôi biết tôi có thể sử dụng một cái gì đó như thế này:Lấy nguyên tố phổ biến nhất trong mảng

most_common = collections.Counter(array).most_common(to_find) 

Tuy nhiên, tôi dường như không thể tìm thấy bất cứ điều gì có thể so sánh, cho việc tìm kiếm các nguyên tố phổ biến nhất .

Tôi có thể lấy đề xuất về cách thực hiện hay không.

Trả lời

10

Vay nguồn gốc của collections.Counter.most_common và đảo ngược nếu thích hợp:

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)] 
>>> 
22

most_common mà không có bất kỳ đối số nào trả về tất cả các mục nhập, được sắp xếp từ phổ biến nhất đến ít nhất.

Vì vậy, để tìm thông tin ít phổ biến nhất, chỉ cần bắt đầu xem từ đầu kia.

+0

Ahh tuyệt vời Tôi hiểu ngay bây giờ. Cảm ơn. – jimy

4
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:])) 
+0

Tuyệt vời. Cảm ơn. – jimy

4

gì về

least_common = collections.Counter(array).most_common()[-1] 
0

Bạn có thể sử dụng một chức năng quan trọng:

>>> data=[1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4] 
>>> min(data,key=lambda x: data.count(x)) 
1 
>>> max(data,key=lambda x: data.count(x)) 
4 
1

Tôi đoán bạn cần điều này:

least_common = collections.Counter(array).most_common()[:-to_find-1:-1] 
1

tôi xin đề nghị như sau,

least_common = collections.Counter(array).most_common()[len(to_find)-10:len(to_find)] 
0

Dựa trên câu trả lời này cho các yếu tố phổ biến nhất: https://stackoverflow.com/a/1518632

Đây là một lót một cho việc thu thập các yếu tố chung nhất trong một danh sách:

def least_common(lst): 
    return min(set(lst), key=lst.count) 
Các vấn đề liên quan