Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find unique pairs in list of pairs

Tags:

python

list

I have a (large) list of lists of integers, e.g.,

a = [
    [1, 2],
    [3, 6],
    [2, 1],
    [3, 5],
    [3, 6]
    ]

Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., [1, 2] is equivalent to [2, 1]). I'd now like to find the pairs that appear only once, and get a Boolean list indicating that. For the above example,

b = [False, False, False, True, False]

Since a is typically large, I'd like to avoid explicit loops. Mapping to frozensets may be advised, but I'm not sure if that's overkill.

like image 984
Nico Schlömer Avatar asked Jul 04 '16 14:07

Nico Schlömer


1 Answers

ctr = Counter(frozenset(x) for x in a)
b = [ctr[frozenset(x)] == 1 for x in a]

We can use Counter to get counts of each list (turn list to frozenset to ignore order) and then for each list check if it only appears once.

like image 62
petabyte Avatar answered Oct 16 '22 03:10

petabyte