Jan
Jan

Reputation: 747

Finding the intersection in two lists of tuples regardless of tuple order

I have two lists of tuples

listA = [('1','2'),('3','4'),('5','6')]
listB = [('2','1'),('7','8')]

I want to find the intersection of them even if the order of the tuple in the second list is different.

So, for the example above:

intersection = [('1','2')]

the intersection should return the tuple above though it is not in the same order in listB

How can I do that in python the most efficient way? because each of my list has around 2000 tuples.

Upvotes: 2

Views: 2451

Answers (3)

Underoos
Underoos

Reputation: 5190

  1. Try to sort the tuples in list.

  2. Convert lists to sets.

  3. Print the intersection of sets.

    listA = [('1','2'),('3','4'),('5','6')]
    listB = [('2','1'),('7','8')]
    for i, j in enumerate(listA):
        listA[i] = tuple(sorted(j))
    for i, j in enumerate(listB):
        listB[i] = tuple(sorted(j))
    listA = set(listA)
    listB = set(listB)
    print(list(listA.intersection(listB)))
    

Output:

[('1', '2')]

Upvotes: 2

L3viathan
L3viathan

Reputation: 27333

>>> set(map(frozenset, listA)) & set(map(frozenset, listB))
{frozenset({'1', '2'})}

Note that this assumes uniqueness in the tuples (i.e. there's no tuple ('1', '1')).

Upvotes: 1

vurmux
vurmux

Reputation: 10030

You can sort each element in lists, convert them to tuples, then convert lists to sets and check sets intersection:

set(
    [
        tuple(sorted(elem))
        for elem in listA
    ]
) & set(
    [
        tuple(sorted(elem))
        for elem in listB
    ]
)

returns:

{('1', '2')}

Upvotes: 4

Related Questions