Python中两组元组的区别

时间:2016-05-24 19:30:04

标签: python python-2.7

我有两组元组ab

a = set([(1,'a'),(34,'b'), (82,'c')])
b = set([(8,'a'),(98,'c')])

我想要一套c,以便

c = set([(34,'b')])

在python中执行此操作的最有效方法是什么?

2 个答案:

答案 0 :(得分:5)

我猜O(n)效率最高:

>>> b2 = {x for n,x in b}
>>> c = {(n,x) for (n,x) in a if x not in b2}
>>> c
{(34, 'b')}

答案 1 :(得分:0)

我首先使用dicts代替a和b的集合:

a = {k: v for (v, k) in a}
b = {k: v for (v, k) in b}

然后,只需要将a的内容置于b

之内
print [(k, a[k]) for k in set(a.keys()) - set(b.keys())]

b_keys = set(b.keys())
print [(k,v) for (k,v) in a.items() if k not in b_keys}