以下是一些使用 dicts 做你想做的事情的方法。这是 Python 2 代码;它需要对 Python 3 进行一些小的修改。IIRC,Python 3 没有,dict.iteritems()
因为它dict.items()
返回一个迭代器而不是一个列表。
A = [('x1','y1'), ('x2','y2'), ('x3','y3')]
B = [('x1','y1'), ('x2','y5'), ('x4','y4')]
dA = dict(A)
dB = dict(B)
#Intersection, the simple way
print 'Result 1a:', list(set(A) & set(B))
#Intersection using dicts instead of sets
result = [(k, vA) for k, vA in dA.iteritems() if dB.get(k) == vA]
print 'Result 1b:', result
#match on 1st tuple element, ignoring 2nd element
result = {}
for k, vA in dA.iteritems():
vB = dB.get(k)
if vB:
result[k] = (vA, vB) if vB != vA else vA
print 'Result 2a:', result.items()
#match on 1st tuple element only if 2nd elements don't match
result = {}
for k, vA in dA.iteritems():
vB = dB.get(k)
if vB and vB != vA:
result[k] = (vA, vB)
print 'Result 2b:', result.items()
#unique elements of B, ignoring 2nd element
result = [(k, vB) for k, vB in dB.iteritems() if k not in dA]
print 'Result 3:', result
输出
Result 1a: [('x1', 'y1')]
Result 1b: [('x1', 'y1')]
Result 2a: [('x2', ('y2', 'y5')), ('x1', 'y1')]
Result 2b: [('x2', ('y2', 'y5'))]
Result 3: [('x4', 'y4')]