Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining nested lists according to first element

So I have three lists:

lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]

What I want to do is to go through the lists and create the following tuple:

[(test1, 0.2, 5.2, 19.2), (test2, 0.0, 11.1, 12.1), (test7, 0.2, 0.2, 19.2), (test9, 0.0, 0.0, 15.1)]

I have tried to solve this through multiple methods but no luck, any help is welcomed!

like image 650
apol96 Avatar asked Oct 28 '25 15:10

apol96


1 Answers

If you really want to use test1 etc. as unique keys, you might be better off using a dictionary.

I'd recommend the following: Use itertools.chain to combine the lists that you want to iterate over, and use a default dictionary that you simply append items to.

import itertools as it
from collections import defaultdict

lst1 = [('test1', 0.2), ('test7', 0.2)]
lst2 = [('test1', 5.2), ('test2', 11.1), ('test7', 0.2)]
lst3 = [('test1', 19.2), ('test2', 12.1), ('test7', 19.2), ('test9', 15.1)]


mydict = defaultdict(list)

for key, value in it.chain(lst1, lst2, lst3):
  mydict[key].append(value)

print(mydict)

> defaultdict(
        <class 'list'>,
        {'test1': [0.2, 5.2, 19.2],
        'test7': [0.2, 0.2, 19.2],
        'test2': [11.1, 12.1],
        'test9': [15.1]}
)
like image 81
Daniel Lenz Avatar answered Oct 31 '25 04:10

Daniel Lenz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!