In python how can I match two lists of tuples by a tuple element?
Let's say I have names
as a list of tuples that contain name tuples in arbitrary order:
names = [(1,"Alice"), (2,"Bob")]
and genders
as another list of tuples that contain gen开发者_如何学Cder tuples in arbitrary order:
genders = [(2,"male"), (1,"female")]
How can I effectively match the two lists by using the first elements of the tuples as a key to get:
result = [("Alice","female"), ("Bob","male")]
Easy one-liner answer, runs slowly:
[(name, gender) for (id0, gender) in genders for (id1, name) in names if id0==id1]
Better answer (see Ignazio's response):
namedict = dict(names)
genderdict = dict(genders)
[(namedict[id], genderdict[id]) for id in set(namedict) & set(genderdict)]
Convert to dictionaries, gather the keys, and iterate.
精彩评论