lelandstanfordjr lelandstanfordjr - 1 year ago 105
Python Question

Python: match lists in two lists of lists

I have two lists of lists. The first is composed of lists formatted as follows:

listInA = [id, a1, a2, a3]

The second is composed of lists formatted similarly, with the id first:

listInB = [id, b1, b2, b3]

Neither list is sorted, and they are not of equal lengths. What is the best way to make a list of lists, with each list of the format:

listInC = [id, a1, a2, a3, b1, b2, b3]

where the id's are matched between both lists? Thanks!

Answer Source

You can create a dictionary using dict comprehension from the second list of lists from ID to list. Then, create your new list using list comprehension, appending the list based on IDs.

listA = [
    [1, 'a', 'b', 'c'],
    [2, 'd', 'e', 'f'],
listB = [
    [2, 'u', 'v', 'w'],
    [1, 'x', 'y', 'z'],

b_map = {b[0]: b for b in listB}
print([a + b_map[a[0]][1:] for a in listA])


    [1, 'a', 'b', 'c', 'x', 'y', 'z'],
    [2, 'd', 'e', 'f', 'u', 'v', 'w']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download