Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building tuples from nested lists

Tags:

python

list

Hi please how can I append the tuples in a nested list to list of dictionaries to form a new list of tuples as follow:

nde = [{'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9},
           {'length': 0.48, 'modes': 'cw', 'type': '99', 'lanes': 9},
           {'length': 0.88, 'modes': 'cw', 'type': '99', 'lanes': 9}]

dge = [[(1001, 7005),(3275, 8925)], [(1598,6009),(1001,14007)]]

How can I append them to have the outcome formatted thus:

rslt = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}... ]

I tried this:

[(k1[0], k1[1], k2) for k1, k2 in zip(dge, nde)]

but it doesnt give the desired result. Thanks

like image 677
user3481663 Avatar asked Mar 20 '23 01:03

user3481663


1 Answers

You need to flatten the list of lists first and then use it with zip:

>>> from itertools import chain
>>> [(k1[0], k1[1], k2) for k1, k2 in zip(chain.from_iterable(dge), nde)]
[(1001, 7005, {'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}),
 (3275, 8925, {'lanes': 9, 'length': 0.48, 'type': '99', 'modes': 'cw'}),
 (1598, 6009, {'lanes': 9, 'length': 0.88, 'type': '99', 'modes': 'cw'})]

Docs: itertools.chain.from_iterable

like image 149
Ashwini Chaudhary Avatar answered Mar 27 '23 20:03

Ashwini Chaudhary