在python中计算和附加子列表元素

在python中计算和附加子列表元素,python,sublist,Python,Sublist,我试图计算子列表元素的唯一实例数,然后将每个唯一元素写入一个新列表,并将实例数附加到子列表中。列表_1中的每个子列表将只有两个元素,顺序并不重要 因此: 变成: new_list = [[a, b, 1], [a, c, 3], [b, e, 1], [d, q, 2]] 我想我需要使用集合,但我很感激有人给我指出了正确的方向计数器对象为多组(也称为行李);他们将关键点映射到他们的计数 您必须将子列表转换为元组才能用作键: from collections import Counter c

我试图计算子列表元素的唯一实例数,然后将每个唯一元素写入一个新列表,并将实例数附加到子列表中。列表_1中的每个子列表将只有两个元素,顺序并不重要

因此:

变成:

new_list =  [[a, b, 1], [a, c, 3], [b, e, 1], [d, q, 2]]
我想我需要使用集合,但我很感激有人给我指出了正确的方向<代码>计数器对象为多组(也称为行李);他们将关键点映射到他们的计数

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

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()]
这将为您提供一个按计数排序的新列表(降序):

如果事件始终是连续的,则还可以使用:

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

这使得:

>>> 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]]

并保留了原来的顺序。

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

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

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

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]]

你能详细说明一下
[a,c,3],[a,c,1]
?同样,
列表中的相同元素是否保证是连续的?这些元素必须是
列表()
s还是
元组()
s?小诡辩:根据定义,唯一元素的实例数正好是1。我想你的意思是,你想计算一下
列表1
中每一对的出现次数?删除[a,c,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]]
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
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]]