【问题标题】:how to merge multiple list in one dict in python?如何在python中的一个字典中合并多个列表?
【发布时间】:2021-07-17 23:00:31
【问题描述】:

示例 = 我有一个这样的字典

{10: [10, 12, 13], 11: [11], 12: [14,15],15:[16]}

我想要这种类型的输出

{10: [12:[14,15:[16]], 13],11:[]}

【问题讨论】:

  • 您想要的输出不是有效的 Python。
  • 恭喜,您的问题收到了我的第 200 次编辑!耶!!!至于实际问题,请解释您为什么想要这种输出。它是基于某种过滤器还是什么?
  • 可能你的意思是嵌套字典,不是吗?
  • 我不明白你的输出。看起来您想组合事物以消除重复项,但这并不能解释为什么“11:[11]”能够幸存下来。如果您从“10”列表中删除了“10”,那么它应该是“11:[]”。对吗?
  • @GauravSolanki 不过,输出没有多大意义...[14,15:[16]] 的格式错误,无论是字典还是列表。

标签: python arrays python-3.x list


【解决方案1】:

以下代码适用于您的示例输入。 我不确定它是否适用于其他输入。 此外,也许它不是实施得最好的程序。 但我希望它会有所帮助。

input = {10: [10, 12, 13], 11: [11], 12: [14, 15], 15: [16]}
# {10: [12:[14,15:[16]], 13],11:[]}
key_not_checked = {n: True for n in input}
output = {}


def check_elemnt_inlist(element):
    value = input.get(element, None)
    if not value:
        return element
    elif len(value) == 1:
        key_not_checked[element] = False
        return {element: value}
    else:
        nested = {}
        val = []
        for i in value:
            if int(i) != int(element):
                val.append(check_elemnt_inlist(i))
        nested[element] = val
        key_not_checked[element] = False
        return nested


for key in input:
    top_value = input[key]
    c = []
    if key_not_checked[key]:
        for g in top_value:
            if int(g) != int(key):
                c.append(check_elemnt_inlist(g))
        output[key] = c
    key_not_checked[key] = False

print(output)

输出将是这样的:

{10: [{12: [14, {15: [16]}]}, 13], 11: []}

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多