Skip to main content
 首页 » 编程设计

python之计算列表列表中每个唯一项的出现次数

2025年05月04日14shanyou

我有一个列表,如下所示:

listoflist = [["A", "B", "A", "C", "D"], ["Z", "A", "B", "C"], ["D", "D", "X", "Y", "Z"]] 

我想找到 listoflist 中每个唯一值出现的子列表的数量。例如,“A”出现在两个子列表中,而“D”也出现在两个子列表中,即使它在 listoflist[3] 中出现了两次。

我怎样才能得到一个数据框,它在一列中包含每个唯一元素和频率(每个唯一元素出现在子列表中的数量)?

请您参考如下方法:

您可以使用:itertools.chain 和 collections.Counter:

In [94]: import itertools as it 
 
In [95]: from collections import Counter 
 
In [96]: Counter(it.chain(*map(set, listoflist))) 
Out[96]: Counter({'A': 2, 'B': 2, 'C': 2, 'D': 2, 'X': 1, 'Y': 1, 'Z': 2}) 

正如@Jean-François Fabre 在评论中提到的,您还可以使用:

In [97]: Counter(it.chain.from_iterable(map(set, listoflist))) 
Out[97]: Counter({'A': 2, 'B': 2, 'C': 2, 'D': 2, 'X': 1, 'Y': 1, 'Z': 2})