在 python 中初始化整数数组最快的方法是什么?
假设我想在 python 中创建一个包含 1,000,000 个二进制的数组(不是列表),如下所示:
array = [2, 2, 2, ...... , 2]
什么是快速但简单的方法呢?
Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:
array = [2, 2, 2, ...... , 2]
What would be a fast but simple way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当前接受的答案不是使用 array.array 的最快方法;至少它不是最慢的——比较一下:
比例约为 9 比 1 ...
The currently-accepted answer is NOT the fastest way using
array.array
; at least it's not the slowest -- compare these:That's a ratio of about 9 to 1 ...
这就是你所追求的吗?
您可以获得一个列表:
--已编辑--
我更新了此内容以反映另一个答案中的信息。看来,通过稍微调整语法,您可以将速度提高约 9 : 1 的比例。全部功劳属于@john-machin。我不知道你可以像对列表那样对数组对象进行倍增。
Is this what you're after?
You can get just a list with this:
-- EDITED --
I updated this to reflect information in another answer. It would appear that you can increase the speed by a ratio of ~ 9 : 1 by adjusting the syntax slightly. Full credit belongs to @john-machin. I wasn't aware you could multiple the array object the same way you could do to a list.
混合方法对我来说效果最快
A hybrid approach works fastest for me
使用 timeit 模块,您可以找出最快 这样做的方法是:
首先,将这么多数字放入列表中很可能会杀死您的机器,因为它将把它存储在内存中。
但是,您可以使用类似的方法来测试执行情况。在我放弃之前,它在我的计算机上运行了很长一段时间,但我使用的是一台旧电脑:
您可以查看的其他选项是使用 array 模块,如上所述,
高效数值数组
我没有测试两者的完成时间,但我确信
array
模块,专为数字集设计,速度会更快。编辑:更有趣的是,你可以看看 numpy 它实际上似乎执行速度最快:
评论甚至更快:
太棒了!
Using the timeit module you can kind of figure out what the fastest of doing this is:
First off, putting that many digits in a list will kill your machine most likely as it will store it in memory.
However, you can test the execution using something like so. It ran on my computer for a long time before I just gave up, but I'm on an older PC:
Ther other option you can look into is using the array module which is as stated,
efficient arrays of numeric values
I did not test the completion time of both but I'm sure the
array
module, which is designed for number sets will be faster.Edit: Even more fun, you could take a look at numpy which actually seems to have the fastest execution:
Even faster from the comments:
Awesome!
或基于昌西链接
or base on chauncey link
如果初始值不必非零,并且您的平台上有 /dev/zero 可用,则以下解决方案比 array('L',[0])*size 解决方案快约 4.7 倍
:问题 如何初始化整数数组。 Python 中带零的数组对象 我正在寻找更好的方法。
If the initial value doesn't have to be non-zero and if you have /dev/zero available on your platform, the following is about 4.7 times faster than the array('L',[0])*size solution:
In question How to initialise an integer array.array object with zeros in Python I'm looking for a better way.