我认为您可以考虑collections.namedtuple
为此目的使用:
>>> from collections import namedtuple
>>> MakeOrigin = namedtuple('MakeOrigin', ['make', 'origin'])
>>> MakeModel = namedtuple('MakeModel', ['make', 'model'])
>>> A = [MakeModel('Chevy', 'Suburban'), MakeModel('Toyota', 'Camry'), MakeModel('Honda', 'Civic')]
>>> B = [MakeOrigin('Chevy', 'America'), MakeOrigin('Toyota', 'Japan'), MakeOrigin('Honda', 'Japan')]
>>> AB = [[a.make, a.model, b.origin] for a in A for b in B if a.make == b.make]
>>> AB
[['Chevy', 'Suburban', 'America'], ['Toyota', 'Camry', 'Japan'], ['Honda', 'Civic', 'Japan']]
它更具可读性并允许更多有趣的操作。
不使用namedtuple
:
>>> A=[['Chevy','Suburban'],['Toyota','Camry'],['Honda','Civic']]
>>> B=[['Chevy','America'],['Toyota','Japan'],['Honda','Japan']]
>>>
>>> AB = [[a[0], a[1], b[1]] for a in A for b in B if a[0] == b[0]]
>>> AB
[['Chevy', 'Suburban', 'America'], ['Toyota', 'Camry', 'Japan'], ['Honda', 'Civic', 'Japan']]