簡體   English   中英

計算Python中的列表列表中列表的出現

[英]Count occurrence of a list in a List of Lists in Python

我有一個看起來像這樣的列表:

co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]. . . ]

我需要計算相同坐標列表的數量並返回計數,在這種情況下為4。

到目前為止,我已經嘗試過:

def most_common(lst):
    lst = list(lst)
    return max(set(lst), key=lst.count)

for each in kk :
    print most_common(each) 

使用它,我可以在每個列表中獲得最多的元素。 但我的意圖是獲取列表(如果出現的次數大於3)。

預期產量:

(element, count) = ([397, 994, 135, 941], 4) 

任何幫助,將不勝感激。 謝謝。

您可以將collections.Counter用於該任務:

from collections import Counter

co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]]

common_list, appearances = Counter([tuple(x) for x in co_list]).most_common(1)[0]  # Note 1
if appearances > 3:
    print((list(common_list), appearances))  # ([397, 994, 135, 941], 4)
else:
    print('No list appears more than 3 times!')

1)內部list s被轉換為tuple s,因為Counter生成了一個dict並且不可哈希的list s不能用作key s。

from collections import Counter

def get_most_common_x_list(origin_list, x):

    counter = Counter(tuple(item) for item in origin_list)

    for item, count in most_common_list = counter.most_common():

        if count > x:

            yield list(item), count

        else:

            break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM