Extract common element from 2 tuples python [duplicate]

走远了吗. 提交于 2020-03-05 03:49:11

问题


I have 2 tuples A & B. How can I extract the common elements of A & B to form a new tuple? For example:

    A -> (1,'a',(2,'b'),3,'c',4)
    B -> (1,(2,'b'),4,8)
    new_tuple -> (1,(2,'b'),4)

Thanks.


回答1:


With set intersection (to return a new set with elements common to the set and all others):

A = (1,'a',(2,'b'),3,'c',4)
B = (1,(2,'b'),4,8)
result = tuple(set(A) & set(B))

print(result)

The output:

(1, 4, (2, 'b'))

https://docs.python.org/3/library/stdtypes.html?highlight=set#frozenset.intersection




回答2:


You could use set intersection. Note that this doesn't guarantee anything about the order of the elements.

>>> A = (1,'a',(2,'b'),3,'c',4)
>>> B = (1,(2,'b'),4,8)
>>> tuple(set(A).intersection(set(B)))
(1, (2, 'b'), 4)


来源:https://stackoverflow.com/questions/46405959/extract-common-element-from-2-tuples-python

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