[英]Looking for an elegant way of finding the intersection between two lists of words' tuples in different orders
[英]Finding the intersection in two lists of tuples regardless of tuple order
我有兩個元組列表
listA = [('1','2'),('3','4'),('5','6')]
listB = [('2','1'),('7','8')]
即使第二個列表中元組的順序不同,我也想找到它們的交集。
所以,對於上面的例子:
intersection = [('1','2')]
交集應該返回上面的元組,盡管它在 listB 中的順序不同
我怎樣才能以最有效的方式在 python 中做到這一點? 因為我的每個列表都有大約 2000 個元組。
您可以對列表中的每個元素進行排序,將它們轉換為元組,然后將列表轉換為集合並檢查集合交集:
set(
[
tuple(sorted(elem))
for elem in listA
]
) & set(
[
tuple(sorted(elem))
for elem in listB
]
)
返回:
{('1', '2')}
1.嘗試對列表中的元組進行排序。
2.將列表轉換為集合。
3.打印集合的交集。
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)))
輸出:
[('1', '2')]
>>> set(map(frozenset, listA)) & set(map(frozenset, listB))
{frozenset({'1', '2'})}
請注意,這假定元組中的唯一性(即沒有元組('1', '1')
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.