【问题标题】:Create a list of dictionaries from a global variable using map or comprehension list python使用映射或理解列表python从全局变量创建字典列表
【发布时间】:2017-09-30 06:37:32
【问题描述】:

我有一个字典作为全局变量和一个字符串列表:

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() 函数来做到这一点

【问题讨论】:

  • 你的代码不会给你想要的结果。
  • @DanielRoseman 修复了它

标签: python python-3.x dictionary list-comprehension map-function


【解决方案1】:

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

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

甚至更好(仅限 Python 3)

[{**GLOBAL, "second": w} for w in word]

【讨论】:

  • python3解决方案怎么来的?
  • @obgnaw 你说的“怎么来”是什么意思
  • 您如何获得解决方案?从未见过{**GLOBAL, "second": w}before。
  • 哦!所以,如果你看过的话,它有点像 def f(**kwargs) 的反面。它本质上将字典用作关键字参数。所以 f(**{"a": 1, "b:2}) 和 f(a=1, b=2) 是一样的。你也可以在字典里这样做!我不知道叫什么名字这是,但它可能在文档的“关键字参数”部分
【解决方案2】:
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)

测试它,然后尝试更多。

【讨论】:

  • 为什么要称这个函数为“hello”?
  • e,只是一个 lambda,我不想重复自己,所以我给它一个简单的名字。@EnricoBorba
【解决方案3】:

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'}]

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2015-05-22
    相关资源
    最近更新 更多