在多维列表中计算相同列表的出现频率?

时间:2015-08-27 12:57:08

标签: python list

我有一个多维列表,如下所示

multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]

如何快速得到以下结果:

[1,2]: count 1 times
[3,4,5]: count 2 times
[5,6]: count 3 times

并获得唯一的多维列表(删除重复项):

multi_list = [[1,2],[3,4,5],[5,6]]

非常感谢。

6 个答案:

答案 0 :(得分:1)

您可以使用可清除的元组collections.Counter

>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> multituples = [tuple(l) for l in multilist]
>>> from collections import Counter
>>> tc = Counter(multituples)
>>> tc
Counter({(5, 6): 3, (3, 4, 5): 2, (1, 2): 1})

要获得元素集,您只需要键:

>>> tc.keys()
dict_keys([(1, 2), (3, 4, 5), (5, 6)])

答案 1 :(得分:1)

如果您想保证唯一项目的顺序与原始列表中的顺序相同,您可以执行以下操作:

>>> class Seen(set):
...     def __contains__(self, item):
...         res = super(Seen, self).__contains__(item)
...         self.add(item)
...         return res
...
>>> seen = Seen()
>>> [item for item in multilist if tuple(item) not in seen]
[[1, 2], [3, 4, 5], [5, 6]]
>>>

答案 2 :(得分:0)

你可以这样试试,

>>> multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
>>> c = [multilist.count(l) for l in multilist]
>>> for ind, l in enumerate(multilist):
...   print( "%s: count %d times" % (str(l), c[ind]))
... 
[1, 2]: count 1 times
[3, 4, 5]: count 2 times
[3, 4, 5]: count 2 times
[5, 6]: count 3 times
[5, 6]: count 3 times
[5, 6]: count 3 times

>>> {str(item): multilist.count(item) for item in multilist }
{'[1, 2]': 1, '[3, 4, 5]': 2, '[5, 6]': 3}

答案 3 :(得分:0)

正如@ReutSharabani建议的那样,你可以使用元组作为字典键,然后转换回列表以便显示。下面的代码不会在collections上回复(并不是说有任何问题)。

multilist = [[1,2],[3,4,5],[3,4,5],[5,6],[5,6],[5,6]]
histogram = {}
for x in multilist:
    xt = tuple(x)
    if xt not in histogram:
        histogram[xt] = 1
    else:
        histogram[xt] += 1
for k,c in histogram.items():
    print "%r: count %d times" % (list(k),c)
print [list(x) for x in histogram.keys()]

答案 4 :(得分:0)

如何使用repr(alist)将其转换为文本字符串表示形式?

from collections import defaultdict

d = defaultdict(int)
for e in multilist: d[ repr(e)] += 1

for k,v in d.items(): print "{0}: count {1} times".format( k,v)

答案 5 :(得分:-1)

您可以使用字典

count_data = {}

for my_list in multilist:
    count_data.setdefault(tuple(my_list), 0)
    count_data[tuple(my_list)] += 1