Skip to main content
 首页 » 编程设计

python之计算 Python 列表列表中元素的频率

2025年05月04日11tuyile006

比如说,我有以下排序列表:

列表 1:(12,24,36)

list 2:(3,5,12,24)

list 3:(36,41,69)

我想找出每个元素在整个列表列表中出现的频率。我在 python 中想出了一个丑陋的模块,但我想知道是否有一些库函数..

编辑:请在下面找到代码

def find_frequency(transactions,list): 
    freq = 0 
    for items_transaction in transactions: 
        flag = 0 
        for candidate in list: 
            if candidate not in items_transaction: 
                flag = 1 
                break 
        if flag == 0: 
            freq += 1 
    return freq 

请您参考如下方法:

Counter 会做我认为您正在寻找的事情:

>>> from itertools import chain 
>>> from collections import Counter 
>>> list1, list2, list3 = [12,24,36], [3,5,12,24], [36,41,69] 
>>> Counter(chain(list1, list2, list3)) 
Counter({3: 1, 5: 1, 12: 2, 24: 2, 36: 2, 41: 1, 69: 1})