为什么字典的 items 方法比直接迭代快得多?

Why items method for dictionary is so much faster than a straightforward iteration?

我正在练习 LeetCode 并遇到了 this 问题。我只是在python学习算法和数据结构,所以不太了解一些内置方法是如何实现的所以我最初的尝试是(python代码)

return [num for num in Counter(nums) if Counter(nums)[num] == 1]

但在 this testcase. On the other hand, there is a very similar one liner 讨论

上 运行 需要整整 12.82 秒
return [c[0] for c in Counter(nums).items() if c[1] == 1]

使用相同的想法但 运行s 快得多,上述测试用例仅用了 0.0022 秒。为什么运行时间会有这么大的差异?

此代码的问题:

return [num for num in Counter(nums) if Counter(nums)[num] == 1]

就是对于Counter(nums)中的每一个num,你都要新建一个Counter(nums)来判断if条件是真还是假。通过在第二个版本中使用 Counter(nums).items()

return [c[0] for c in Counter(nums).items() if c[1] == 1]

您已经可以访问该号码及其计数,因此无需重新计算每个号码的计数。

注意我会把理解写成

return [num for num, count in Counter(nums).items() if count == 1]

使它的工作原理更加明显。