代码之家  ›  专栏  ›  技术社区  ›  mel

使用映射或理解列表python从全局变量创建字典列表

  •  1
  • mel  · 技术社区  · 7 年前

    GLOBAL = {"first": "Won't change", "second": ""}
    words = ["a", "test"]
    

    我的目标是创建以下列表:

    [{"first": "Won't change", "second": "a"}, {"first": "Won't change", "second": "test"}]
    

    我可以用以下代码来实现:

    result_list = []
    for word in words:
        dictionary_to_add = GLOBAL.copy()
        dictionary_to_add["second"] = word
        result_list.append(dictionary_to_add)
    

    我的问题是如何使用理解列表或map()函数来实现它

    3 回复  |  直到 7 年前
        1
  •  2
  •   Enrico Borba    7 年前

    很确定你可以在一条丑陋的线里做到这一点。假设您使用不可变值,否则您必须进行深度复制,这也是可能的:

    [GLOBAL.copy().update(second=w) for w in word]
    

    [{**GLOBAL, "second": w} for w in word]
    
        2
  •  1
  •   obgnaw    7 年前
    GLOBAL = {"first": "Won't change", "second": ""}
    words = ["a", "test"]
    result_list = []
    for word in words:
        dictionary_to_add = GLOBAL.copy()
        dictionary_to_add["second"] = word
        result_list.append(dictionary_to_add)
    print result_list
    def hello(word):
        dictionary_to_add = GLOBAL.copy()
        dictionary_to_add["second"] = word
        return dictionary_to_add
    print [hello(word) for word in words]
    print map(hello,words)
    

    测试它,并尝试更多。

        3
  •  1
  •   hys    7 年前

    In [106]: def up(x):
         ...:     d = copy.deepcopy(GLOBAL)
         ...:     d.update(second=x)
         ...:     return d
         ...: 
    
    In [107]: GLOBAL
    Out[107]: {'first': "Won't change", 'second': ''}
    
    In [108]: map(up, words)
    Out[108]: 
    [{'first': "Won't change", 'second': 'a'},
     {'first': "Won't change", 'second': 'test'}]