【问题标题】:Populate dict using reduce() instead of loop使用 reduce() 而不是循环填充 dict
【发布时间】:2022-07-15 21:20:00
【问题描述】:

有没有办法通过使用 reduce() 而不是 for 循环来加速这段代码? 我看了很多类似的问题,但没有找到答案。

old_dict = {'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'c', 'd']
new_dict = {}
for key in keys:
    new_dict[key] = old_dict.get(key)
print(new_dict)

# prints:
# {'a': 1, 'c': 3, 'd': None}

【问题讨论】:

    标签: python reduce


    【解决方案1】:

    如果您不打算使用reduce,您可以将几个内置函数链接在一起,这应该非常有效。

    new_dict = dict(zip(keys, map(old_dict.get, keys)))
    

    【讨论】:

      猜你喜欢
      • 2012-03-21
      • 2018-02-22
      • 1970-01-01
      • 2022-11-12
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2020-11-25
      相关资源
      最近更新 更多