【问题标题】:how to avoid for loop to append dictionary values in a list如何避免for循环在列表中附加字典值
【发布时间】:2020-05-16 06:32:15
【问题描述】:

我有这本词典:

Dict = {
    "a" : 1,
    "b" : 2,
    "c" : 3
}

还有这两个列表:

List1 = ["a","c"]
List2 = [0]

有没有比以下方法更有效的方法将 List1 通过 Dict 的相应值附加到 List2 ? :

for e in List1:
    List2.append(Dict[e]) 

结果:

[0, 1, 3]

【问题讨论】:

  • 你可以从字典中获取值:dict.values()。它会返回列表中的所有值
  • list2.extend(Dict[e] for e in List1) ?

标签: python list dictionary for-loop append


【解决方案1】:

在运行时间方面可能没有任何效率,但在编写代码方面效率更高:

List2.extend(Dict[e] for e in List1)

如果你对代码高尔夫感兴趣,

List2.extend(map(Dict.get, List1))

【讨论】:

  • 感谢您的帮助。您知道就两种解决方案之间的运行时间而言最有效的是什么?
  • 对于这个小例子,第二个似乎快了大约 30%,但从绝对意义上讲,差异可以忽略不计(601 ns 对 474 ns),这可能会根据 @ 的大小而改变987654323@ 和Dict。像任何性能测量一样,等到您怀疑某项需要更快,然后再担心它是否可以更快。
猜你喜欢
  • 2020-05-26
  • 2013-08-21
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 2019-07-26
  • 2020-03-26
  • 2021-06-23
相关资源
最近更新 更多