gpt4 book ai didi

python - 以字典为内容的嵌套列表

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:29 24 4
gpt4 key购买 nike

你好,我如何循环遍历下面的 lst2,如果元素匹配,如何获取 lst1 中的字典元素。

lst1 = [[(10, 70, {'a': 0.30}),
(12, 82, {'b': 0.35})],
[(11, 140, {'c': 0.54}),
(99, 25, {'d': 0.57})]
]

lst2 = [[(10, 70), (32, 25),(12,82)],
[(1598, 6009), (11,140), (33,66), (99,25)]
]

即比较 lst2,如果 lst2 在 lst1 中,则打印字典。

结果应该是这样的:

outcome = [[{'a': 0.30}, {'b':0.35}], [{'c': 0.54}, {'d':0.57}]]

谢谢

很抱歉,如果 lst1 没有嵌套,那么对此的更新将是

lst1 = [(10, 70, {'a': 0.30}),
(12, 82, {'b': 0.35}),
(11, 140, {'c': 0.54}),
(99, 25, {'d': 0.57})
]

lst2 = [[(10, 70), (32, 25),(12,82)],
[(1598, 6009), (11,140), (33,66), (99,25)]
]

这样会得到相同的结果

最佳答案

您可以展平 lst1 并将其转换为具有字典推导式的字典,以便查找速度更快。字典构造完成后,只需迭代lst2,如果元素是字典中的键,则获取对应的字典值。

from itertools import chain
d = {(item[0], item[1]):item[2] for item in chain.from_iterable(lst1)}
print d
# {(12,82):{'b':0.3}, (10,70):{'a':0.3}, (11,140):{'c':0.54}, (99,25):{'d':0.57}}
print [[d[item] for item in items if item in d] for items in lst2]
# [[{'a': 0.3}, {'b': 0.3}], [{'c': 0.54}, {'d': 0.57}]]

如果输入没有嵌套,就像更新后的问题一样,您不需要链接。你可以简单地做

d = {(item[0], item[1]):item[2] for item in lst1}

关于python - 以字典为内容的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22779757/

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