是否可以更快地计算列表中数字出现的数量?
我正在尝试编写一个函数来计算列表中数字的出现,并且该顺序是根据数字上升(从列表中的0到最大值)而不是出现。这是我写的功能:
def sort_counts(sample):
result = []
for i in range(max(sample)+1):
result.append(sample.count(i))
return result
例如:
>>> sort_counts([1,2,2,3,3,4,1,1,1,1,2,5])
>>> [0, 5, 3, 2, 1, 1]
我了解到sample.count
如果列表中有更多数字,则可以缓慢工作。我可以编写此功能更快/更简单吗?
I am trying to write a function to count the occurrences of a number in a list, and the order is ascending according to the number (from 0 to the maximum value in the list), not the occurrences. Here's the function I wrote:
def sort_counts(sample):
result = []
for i in range(max(sample)+1):
result.append(sample.count(i))
return result
For example:
>>> sort_counts([1,2,2,3,3,4,1,1,1,1,2,5])
>>> [0, 5, 3, 2, 1, 1]
I learned that sample.count
would work slowly if there are more numbers in the list. Is there a faster/simpler way I can write this function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
收集模块的计数器是计算列表中项目出现数量的好方法
Counter from collections module is a nice way to count the number of occurrences of items in a list
如果您不想使用计数器,则可以在创建适当大小的结果数组之后简单地迭代列表中的值:
输出:
示例数据的速度明智,如果
counter 解决方案是
1x
时间,这是关于4X
和您现有的解决方案,涉及8x
。随着列表的越来越长,Counter
的速度优势降低,相对性能更像1X
,2X
和4X
代码>。If you don't want to use a counter, then you can simply iterate over the values in the list after creating a result array of the appropriate size beforehand:
Output:
Speed wise for your sample data, if the
Counter
solution is1x
time, this is about4x
and your existing solution about8x
. As the lists get longer, the speed advantage ofCounter
decreases and the relative performance is more like1x
,2x
and4x
.如果您不想通过样本的元素使用计数并更新结果。它可以减少找到元素计数所需的多次遍历所需的时间。
If you don't want to use count iterate through the elements of the samples and update the result. It can reduce the time required for multiple traversal required to find the count of the element.