Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of pairs in list disregarding order

In example, if I have the following script:

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

I get as output:

[('a', 'b', 1), ('b', 'a', 1), ('c', 'd', 2), ('d', 'c', 1)]

Can I adapt my code to yield the following output:

[('a', 'b', 2), ('c', 'd', 3)]

So a function that doesn't include the order of the pairs?

like image 349
veerle Avatar asked Nov 29 '25 20:11

veerle


2 Answers

Use a data structure that doesn't care about order. In this case you'll need frozenset instead of a regular set because Counter requires it to be hashable. But basically it's a simple substitution of tuple in your original code for frozenset:

print([(a, b, v) for (a, b),v in collections.Counter(map(frozenset,lst)).items()])

Output:

[('a', 'b', 2), ('d', 'c', 3)]
like image 162
Dan Avatar answered Dec 01 '25 11:12

Dan


You could just sort each element in the list before counting, like so:

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

Output:

[('a', 'b', 2), ('c', 'd', 3)]
like image 37
CDJB Avatar answered Dec 01 '25 11:12

CDJB