简体   繁体   中英

Combining 2 lists of lists in python

I am newbie in python. I need to merge 2 lists of lists based on the first element in each list. Here are the lists:

first_list = [['aaa', 551, 10972],
              ['bbb', 552, 10872],
              ['ccc', 553, 11103],
              ['ddd', 554, 10912]]

second_list = [['aaa', 240], 
               ['bbb', 120], 
               ['ccc', 325], 
               ['ddd', 270]]

The code I have written:

join_list = []
for x in range(0, len(first_list)):
    temp = [first_list[x], second_list[x][1]]
    join_list.append(temp)

The following is the output:

join_list =
[[['aaa', 551, 10972], 240],
 [['bbb', 552, 10872], 120],
 [['ccc', 553, 11103], 325],
 [['ddd', 554, 10912], 270]]

I need to flatten the list of the list in each element in join_list , eg the first element in join_list[0] = ['histogram', 551, 10972, 240] . Also, if the order of the second list is change and if there is an addition of a sublist in the first element, the 2 lists is still can be merged based on the first index in each element. So, it works like the VLOOKUP or HLOOKUP in Ms.Excel. How can we do this?

This is one way which does not assume a specific ordering of either list.

d = dict(second_list)

res = [i + [d[i[0]]] for i in first_list]

[['aaa', 551, 10972, 240],
 ['bbb', 552, 10872, 120],
 ['ccc', 553, 11103, 325],
 ['ddd', 554, 10912, 270]]

You could introduce lookup dict and set default value in case there is no match:

lookup = dict(second_list)
default = 0
join_list = [i + [lookup.get(i[0], default)] for i in first_list]

Here, default is set to 0 .

Use chain from itertools to flatten

Demo:

first_list = [['aaa', 551, 10972],
              ['bbb', 552, 10872],
              ['ccc', 553, 11103],
              ['ddd', 554, 10912]]

second_list = [['aaa', 240], 
               ['bbb', 120], 
               ['ccc', 325], 
               ['ddd', 270]]

from itertools import chain
print([list(chain(*[v, [second_list[i][1]]])) for i, v in enumerate(first_list)])

Output:

[['aaa', 551, 10972, 240], ['bbb', 552, 10872, 120], ['ccc', 553, 11103, 325], ['ddd', 554, 10912, 270]]

Maybe this is what you are looking for:

d = dict(second_list)
flat = [a+[d[a[0]]] for a in first_list]

It gives me:

flat = [['aaa', 551, 10972, 240],
 ['bbb', 552, 10872, 120],
 ['ccc', 553, 11103, 325],
 ['ddd', 554, 10912, 270]]

This way the order of your second list does not matter.

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