[英]Building tuples from nested lists
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
谢谢
You need to flatten the list of lists first and then use it with zip
: 您需要首先展平列表列表,然后使用
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
文档:
itertools.chain.from_iterable
You have nested list, so you should flatten them before ziping: 你有嵌套列表,所以你应该在ziping之前展平它们:
import itertools
[(k1[0], k1[1], k2) for k1, k2 in zip(itertools.chain(*dge), nde)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.