不考虑顺序计算列表中的对数
Count number of pairs in list disregarding order
例如,如果我有以下脚本:
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)]
那么一个函数不包括对的顺序?
您可以在计数之前对列表中的每个元素进行排序,如下所示:
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)]
使用不关心顺序的数据结构。在这种情况下,你需要 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)]
您可以对键 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)]
在收集列表之前对列表进行排序可以解决问题。
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()])
例如,如果我有以下脚本:
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)]
那么一个函数不包括对的顺序?
您可以在计数之前对列表中的每个元素进行排序,如下所示:
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)]
使用不关心顺序的数据结构。在这种情况下,你需要 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)]
您可以对键 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)]
在收集列表之前对列表进行排序可以解决问题。
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()])