簡體   English   中英

計算列表列表中列表的出現次數

[英]count occurrence of a list in a list of lists

Python

我有一個列表列表。

A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

我想計算每個列表在主列表中出現的次數。

我的輸出應該像

[x,y] = 2
[a,b] = 2
[c,f] = 1 
[e,f] = 1

只需使用collections中的Counter

from collections import Counter
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

new_A = map(tuple, A) #must convert to tuple because list is an unhashable type

final_count = Counter(new_A)


#final output:

for i in set(A):
   print i, "=", final_count(tuple(i))

您可以使用collections.Counter - 一個 dict 子類 - 來進行計數。 首先,將子列表轉換為元組,使它們可用作(即可散列)字典鍵,然后計數:

from collections import Counter

count = Counter(map(tuple, A))

您還可以使用 pandas 來獲得更簡潔的代碼:

pd.Series(A).explode().value_counts()

根據您的輸出,您可以loopset list並打印每個項目及其原始listcount()

for x in set(map(tuple, A)):
    print '{} = {}'.format(x, A.count(list(x)))

暫無
暫無

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

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