Heim  >  Fragen und Antworten  >  Hauptteil

Bitte helfen Sie mir, einen Teil des göttlichen Python-Codes zu interpretieren, danke! !

def combine_dicts(a, b):
    if b is None:
        return a
    return dict(a.items() + b.items() +
                [(k, combine_dicts(a[k], b[k])) for k in set(b) & set(a)])

a und b sollten beide Daten vom Typ Diktat sein, insbesondere die letzte Rückgabe. ?

学习ing学习ing2667 Tage vor777

Antworte allen(3)Ich werde antworten

  • 为情所困

    为情所困2017-06-30 09:57:56

    这是 Python 2 的写法。来个 Python 3.6 版:

    def dict_deep_merge(a, b):
      if not b:
        return a
      return {**a, **b,
        **{k: dict_deep_merge(a[k], b[k])
           for k in set(a) & set(b)}}

    应该高效一点。别的差不多。

    并不算什么神级代码,也不是很难理解。递归合并相同 key 的值而已。你需要知道的知识点:

    • dict 的 items 方法

    • tuple 的相加

    • 集合的交

    • dict 参数的意义

    Antwort
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-30 09:57:56

    函数的作用合并两个dict
    比如
    a = {'a': {'A': 1}, 'b': 1}
    b = {'a': {'B': 1}}
    合并成
    {'a': {'A': 1, 'B': 1}, 'b': 1}
    
    set(b) & set(a)是取a,c的key交集,如上a,b的key交集为a, 再递归运行子dict

    Antwort
    0
  • 阿神

    阿神2017-06-30 09:57:56

    提问一下,代码是有一定的问题吧,如果相同的key里,value值是字符串的话,items这个函数会报错吧?

    Antwort
    0
  • StornierenAntwort