gpt4 book ai didi

python - 从嵌套列表构建元组

转载 作者:太空狗 更新时间:2023-10-30 02:20:30 25 4
gpt4 key购买 nike

您好,请问如何将嵌套列表中的元组附加到字典列表中以形成新的元组列表,如下所示:

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)]]

我如何附加它们以使结果格式化:

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

我试过这个:

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

但它没有给出预期的结果。谢谢

最佳答案

您需要先将列表的列表展平,然后将其与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'})]

文档:itertools.chain.from_iterable

关于python - 从嵌套列表构建元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22773052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com