我正在尝试计算子列表元素的唯一实例的数量,然后将每个唯一元素写入新列表,并将实例数附加到子列表。 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]]
我在想我需要使用套装,但我感谢任何指点我正确方向的人。
答案 0 :(得分: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]]
并保留原始订单。
答案 1 :(得分: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]]
答案 2 :(得分: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