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

余生长醉 提交于 2021-02-05 07:32:45

问题


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.


回答1:


>>> 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')).




回答2:


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')}




回答3:


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


来源:https://stackoverflow.com/questions/56149978/finding-the-intersection-in-two-lists-of-tuples-regardless-of-tuple-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!