例如,如果我有以下脚本:
import collections
lst = [['a','b'],['b','a'],['c','d'],['c','d'],['d','c']]
print([(a, b, v) for (a, b),v in collections.Counter(map(tuple,lst)).items()])
我得到作为输出:
[('a', 'b', 1), ('b', 'a', 1), ('c', 'd', 2), ('d', 'c', 1)]
我可以调整我的代码以产生以下输出吗:
[('a', 'b', 2), ('c', 'd', 3)]
那么一个不包括对顺序的函数?
使用不关心顺序的数据结构。在这种情况下,您将需要frozenset
而不是常规set
Counter
因为它需要可哈希处理。但基本上它是将原始代码中的tuple
简单地替换为frozenset
:
print([(a, b, v) for (a, b),v in collections.Counter(map(frozenset,lst)).items()])
输出:
[('a', 'b', 2), ('d', 'c', 3)]
您可以在计数之前对列表中的每个元素进行排序,如下所示:
import collections
lst = [['a','b'],['b','a'],['c','d'],['c','d'],['d','c']]
sorted_lst = [sorted(x) for x in lst]
print([(a, b, v) for (a, b),v in collections.Counter(map(tuple,sorted_lst)).items()])
输出:
[('a', 'b', 2), ('c', 'd', 3)]
在获取列表集合之前对列表进行排序可以解决问题。
import collections
lst = [['a','b'],['b','a'],['c','d'],['c','d'],['d','c']]
sort_list = sorted(x) for x in lst
print([(a, b, v) for (a, b),v in collections.Counter(map(tuple,sort_list)).items()])
您可以对键a,b
的值进行排序,并在itertools
中使用groupby
,然后sum
组中的所有元素。
import itertools as it
lst = [['a','b'],['b','a'],['c','d'],['c','d'],['d','c']]
output = [(*group,sum(1 for i in elements)) for group,elements in it.groupby(lst,key=lambda x:sorted(x))]
print(output)
输出
[('a', 'b', 2), ('c', 'd', 3)]