在Python中如何找到2个元组中的匹配元素?

时间:2015-02-18 04:00:11

标签: python tuples

让我们说我的名字是包含一些任意字符串数据的元组列表:

tupl2 = ("a", "b", "c")
tupl1 = ("b", "c", "x")

如何将结果作为

matching_elements = "b", "c"

not_matching_elements = "a", "x"

4 个答案:

答案 0 :(得分:2)

看起来你想要交叉和对称差异,你可以轻松地获得这些(如果你不关心订单)使用套装......

>>> tupl2 = ("a", "b", "c")
>>> tupl1 = ("b", "c", "x")
>>> s1 = set(tupl1)
>>> s2 = set(tupl2)
>>> s1.intersection(s2)
set(['c', 'b'])
>>> s1.symmetric_difference(s2)
set(['a', 'x'])

注意,只有第一个实际上需要成为一个集合 - 第二个可以留作元组......

>>> s1.intersection(tupl2)
set(['c', 'b'])
>>> s1.symmetric_difference(tupl2)
set(['a', 'x'])

答案 1 :(得分:0)

使用列表理解很容易在一行中获得交集:

matching = [item for item in tupl1 if item in tupl2]

对称差异有点混乱:

non_matching = ([item for item in tupl2 if item not in tupl1] +
                [item for item in tupl1 if item not in tupl2])

或:

non_matching = [item for item in tupl2 + tupl1
                if item not in tupl1 or item not in tupl2]

老实说,对于后一种情况,我可能会使用set,就像mgilson的回答一样。

答案 2 :(得分:-1)

这是我的答案(修改)

          print set([x for x in list(tupl1 + tupl2) if list(tupl1 + tupl2).count(x) == 2 ])

          print set([x for x in list(tupl1 + tupl2) if list(tupl1 + tupl2).count(x) == 1 ])

答案 3 :(得分:-1)

匹配? 你想找到连续的角色吗? 如果我的推论是正确的,那么这里是您需要的代码:

匹配元素:

a=["a","b","d"]
b=["b","x","c"]
for index in  range(len(a)):
    i, ii = bytes(a[index],'ascii')[0], bytes(b[index],'ascii')[0]
    if i - ii == 1 or ii - i == 1 :
        print(chr(i), chr(ii))

a=["a","b","d"] b=["b","x","c"] for index in range(len(a)): i, ii = bytes(a[index],'ascii')[0], bytes(b[index],'ascii')[0] if i - ii == 1 or ii - i == 1 : print(chr(i), chr(ii))