2

我正在尝试计算子列表元素的唯一实例数,然后将每个唯一元素写入一个新列表,并将实例数附加到子列表中。list_1 中的每个子列表将只有两个元素,顺序无关紧要。

所以:

list_1 = [[a, b], [a, c], [a, c], [a, c], [b, e], [d, q], [d, q]]

变成:

new_list =  [[a, b, 1], [a, c, 3], [b, e, 1], [d, q, 2]]

我在想我需要使用集合,但我感谢任何人指出我正确的方向。

4

3 回答 3

6

你想看collections.Counter()Counter对象是多集(也称为包);他们将键映射到计数。

您必须子列表转换为元组才能用作键:

from collections import Counter

counts = Counter(tuple(e) for e in list_1)

new_list = [list(e) + [count] for e, count in counts.most_common()]

它为您提供new_list按计数排序(降序):

>>> from collections import Counter
>>> list_1 = [['a', 'b'], ['a', 'c'], ['a', 'c'], ['a', 'c'], ['b', 'e'], ['d', 'q'], ['d', 'q']]
>>> counts = Counter(tuple(e) for e in list_1)
>>> [list(e) + [count] for e, count in counts.most_common()]
[['a', 'c', 3], ['d', 'q', 2], ['a', 'b', 1], ['b', 'e', 1]]

如果您的出现总是连续的,那么您也可以使用itertools.groupby()

from itertools import groupby

def counted_groups(it):
    for entry, group in groupby(it, key=lambda x: x):
        yield entry + [sum(1 for _ in group)]

new_list = [entry for entry in counted_groups(list_1)]

我在这里使用了一个单独的生成器函数,但是您可以将循环内联到列表理解中。

这给出了:

>>> from itertools import groupby
>>> def counted_groups(it):
...     for entry, group in groupby(it, key=lambda x: x):
...         yield entry + [sum(1 for _ in group)]
... 
>>> [entry for entry in counted_groups(list_1)]
[['a', 'b', 1], ['a', 'c', 3], ['b', 'e', 1], ['d', 'q', 2]]

并保留原来的顺序。

于 2013-03-02T16:40:22.057 回答
1

如果相同的子列表是连续的:

from itertools import groupby

new_list = [sublist + [sum(1 for _ in g)] for sublist, g in groupby(list_1)]
# -> [['a', 'b', 1], ['a', 'c', 3], ['b', 'e', 1], ['d', 'q', 2]]
于 2013-03-02T16:50:22.907 回答
0

有点“绕房子”的解决方案

list_1 = [['a', 'b'], ['a', 'c'], ['a', 'c'], ['a', 'c'], ['b', 'e'], ['d', 'q'], ['d', 'q']]
new_dict={}
new_list=[]
for l in list_1:
    if tuple(l) in new_dict:
        new_dict[tuple(l)] += 1
    else:
        new_dict[tuple(l)] = 1
for key in new_dict:
    entry = list(key)
    entry.append(new_dict[key])
    new_list.append(entry)
print new_list
于 2013-03-02T16:45:38.727 回答