从 2 个元组 python 中提取公共元素 [英] Extract common element from 2 tuples python
本文介绍了从 2 个元组 python 中提取公共元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个元组 A &B. 我怎样才能提取 A & 的共同元素?B 形成一个新的元组?例如:
A ->(1,'a',(2,'b'),3,'c',4)B->(1,(2,'b'),4,8)new_tuple ->(1,(2,'b'),4)
谢谢.
解决方案
您可以使用集合交集.请注意,这并不能保证元素的顺序.
<预><代码>>>>A = (1,'a',(2,'b'),3,'c',4)>>>B = (1,(2,'b'),4,8)>>>元组(集(A).交集(集(B)))(1, (2, 'b'), 4)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.
解决方案
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)
这篇关于从 2 个元组 python 中提取公共元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文