什么是初始化了一个Python整数数组最快的方法? [英] What is the fastest way to initialize an integer array in python?

查看:453
本文介绍了什么是初始化了一个Python整数数组最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想创造了一个Python 1,000,000两岁阵列(不表),就像这样:

Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:

阵列= [2,2,2,...,2]

什么是做一个快速而简单的方法是什么?

What would be a fast but simple way of doing it?

推荐答案

这是你后?

# slower.
twosArr = array.array('i', [2] * 1000000)

# faster.
twosArr = array.array('i', [2]) * 1000000

您可以得到的只是这个列表:

You can get just a list with this:

twosList = [2] * 1000000

- 编辑 -

-- EDITED --

我更新这反映了另一个答案的信息。这样看来,您可以通过〜9的比例提高速度:1通过稍微调节的语法。完全学分制属于@约翰 - MACHIN。我不知道,你可以多个数组对象,你可以做一个列表的方式相同。

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.

这篇关于什么是初始化了一个Python整数数组最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆