简体   繁体   中英

Matching and Appending

I'm trying to figure out how to run 1 list through another list, and whenever the first names match, append it to the new list if it exists

list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]

list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]

So it looks something like this.

list3 = [["Ryan","Canada","10"],["John","United States","30"],["Jake","Spain","15"]

So far I haven't really been able to even come close, so even the smallest guidance would be much appreciated. Thanks.

You could transform them into dictionaries and then use a list comprehension:

dic1 = dict(list1)
dic2 = dict(list2)
list3 = [[k,dic2[k],dic1[k]] for k in dic2 if k in dic1]

If ordering isn't a concern, the most straightforward way is to convert the lists into more suitable data structures: dictionaries.

ages      = dict(list1)
countries = dict(list2)

That'll make it a cinch to combine the pieces of data:

>>> {name: [ages[name], countries[name]] for name in ages.keys() & countries.keys()}
{'Ryan': ['10', 'Canada'], 'Jake': ['15', 'Spain'], 'John': ['30', 'United States']}

Or even better, use nested dicts:

>>> {name: {'age': ages[name], 'country': countries[name]} for name in ages.keys() & countries.keys()}
{'Ryan': {'country': 'Canada',        'age': '10'},
 'Jake': {'country': 'Spain',         'age': '15'},
 'John': {'country': 'United States', 'age': '30'}}

If the names are unique you can make list1 into a dictionary and then loop through list2 adding items from this dictionary.

list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]
list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]
list1_dict = dict(list1)
output = [item + [list1_dict[item[0]]] for item in list2]

If not, then you need to decide how to deal with cases of duplicate names.

You can use a set and an OrderedDict to combine the common names and keep order:

list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]

list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]


from collections import OrderedDict

# get set of names from list2
names = set(name for name,_ in list2)

# create an OrderedDict using name as key and full sublist as value
# filtering out names that are not also in list2
d = OrderedDict((sub[0], sub) for sub in list1 if sub[0] in names)

for name, country in list2:
     if name in d:
         # add country from  each sublist with common name
         d[name].append(country)

print(d.values()) # list(d.values()) for python3
[['Ryan', '10', 'Canada'], ['John', '30', 'United States'], ['Jake', '15', 'Spain']]

If list2 always has common names you can remove the if name in d:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM