繁体   English   中英

Python 计算列表中列表的重复项

[英]Python count duplicates over lists in list

我有一个包含其他几个列表的列表。 我想计算一个元素在所有这些列表中出现的频率。 例如:

my_list_of_lists=[[1,2,3,4],[1,2],[],[2,3,5]]

输出可能类似于:

1: 2
2: 3
3: 2
4: 1
5: 1

特定元素仅在每个列表中出现。

一些代码将非常有帮助。
谢谢!

>>> from collections import Counter
>>> ct = Counter([jtem for item in a for jtem in item])
>>> ct
Counter({2: 3, 1: 2, 3: 2, 4: 1, 5: 1})

或者

>>> from itertools import chain
>>> from collections import Counter
>>>
>>> ct = Counter(chain.from_iterable(a))
>>> ct
Counter({2: 3, 1: 2, 3: 2, 4: 1, 5: 1})

这应该对你有帮助。

使用Monoid

from collections import Counter    
Counter(sum(my_list_of_lists, []))
d={}
#l is the given list
for l1 in l:
    #l1 is nested list
    for j in l1:
    #j is element
        if j in d.keys():
             d[j]+=1
        else:
             d[j]=1

你有一个 dict d 元素作为键和值作为元素计数。

为了完整起见,您也可以为此使用 numpy:

import numpy as np
my_list_of_lists=[[1,2,3,4],[1,2],[],[2,3,5]]
np_array_of_arrays = np.concatenate([np.array(i) for i in my_list_of_lists])
d = dict(zip(*np.unique(np_array_of_arrays , return_counts=True)))
print(d)

{1.0: 2, 2.0: 3, 3.0: 2, 4.0: 1, 5.0: 1}

首先,你应该扁平化的listlist太会变得,只是list ,你可以做以下的方法:

data = [[1,2,3,4],[1,2],[],[2,3,5]]
flat = sum(data,[])

现在flat[1, 2, 3, 4, 1, 2, 2, 3, 5] ,现在我们可以得到唯一的元素:

uniq = list(set(flat))

最后,我们可以获得出现次数并将其存储在dict

quantity = {i:flat.count(i) for i in uniq}

这是:

print(quantity) #{1: 2, 2: 3, 3: 2, 4: 1, 5: 1}

我想指出,此任务的每个部分都可以以不同的方式完成,最重要的是,我想表明,在将任务划分为子任务后,它可能会变得更容易实现(或找到现成的实现)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM