简体   繁体   English

如何在Python中创建整数数组?

[英]How to create an integer array in Python?

It should not be so hard. 它不应该那么难。 I mean in C, 我的意思是在C,

int a[10]; 

is all you need. 是你所需要的全部。 How to create an array of all zeros for a random size. 如何为随机大小创建全零的数组。 I know the zeros() function in NumPy but there must be an easy way built-in, not another module. 我知道NumPy中的零()函数,但必须有一个简单的内置方法,而不是另一个模块。

two ways: 两种方式:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list. 编辑:用xrange替换range以避免创建另一个列表。

Also: as many others have noted including Pi and Ben James, this creates a list , not a Python array. 另外:正如许多人已经注意到包括Pi和Ben James,这创建了一个list ,而不是Python数组。 While a list is in many cases sufficient and easy enough, for performance critical uses (eg when duplicated in thousands of objects) you could look into python arrays. 虽然列表在许多情况下足够且容易,但对于性能关键用途(例如,当在数千个对象中重复时),您可以查看python数组。 Look up the array module, as explained in the other answers in this thread. 查找array模块,如本主题中的其他答案所述。

If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers: 如果您对列表不满意(因为它们可以包含任何内容并占用太多内存),您可以使用有效的整数数组:

import array
array.array('i')

See here 看到这里

If you need to initialize it, 如果你需要初始化它,

a = array.array('i',(0 for i in range(0,10)))
>>> a = [0] * 10
>>> a
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Use the array module. 使用阵列模块。 With it you can store collections of the same type efficiently. 有了它,您可以有效地存储相同类型的集合。

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - eg different types, look at the documentation of the array module . 有关更多信息 - 例如不同类型,请查看阵列模块的文档 For up to 1 million entries this should feel pretty snappy. 对于多达100万个条目,这应该感觉非常活泼。 For 10 million entries my local machine thinks for 1.5 seconds. 对于1000万个条目,我的本地机器认为1.5秒。

The second parameter to array.array is a generator , which constructs the defined sequence as it is read. array.array的第二个参数是一个生成器 ,它在读取时构造定义的序列。 This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. 这样,阵列模块可以逐个消耗零,但生成器只使用常量内存。 This generator does not get bigger (memory-wise) if the sequence gets longer. 如果序列变长,这个生成器不会变大(内存方面)。 The array will grow of course, but that should be obvious. 阵列当然会增长,但这应该是显而易见的。

You use it just like a list: 你就像列表一样使用它:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list: ...或者只是将其转换为列表:

>>> l = list(a)
>>> len(l)
14

Surprisingly 出奇

>>> a = [0] * 10000000

is faster at construction than the array method. 在构造上比阵列方法更快。 Go figure! 去搞清楚! :) :)

a = 10 * [0]

给你一个长度为10的数组,用零填充。

import random

def random_zeroes(max_size):
  "Create a list of zeros for a random size (up to max_size)."
  a = []
  for i in xrange(random.randrange(max_size)):
    a += [0]

Use range instead if you are using Python 3.x. 如果您使用的是Python 3.x,请使用range

If you need to initialize an array fast, you might do it by blocks instead of with a generator initializer, and it's going to be much faster. 如果你需要快速初始化一个数组,你可以用块而不是生成器初始化器来完成它,它会更快。 Creating a list by [0]*count is just as fast, still. [0]*count创建列表同样快。

import array

def zerofill(arr, count):
    count *= arr.itemsize
    blocksize = 1024
    blocks, rest = divmod(count, blocksize)
    for _ in xrange(blocks):
        arr.fromstring("\x00"*blocksize)
    arr.fromstring("\x00"*rest)

def test_zerofill(count):
    iarr = array.array('i')
    zerofill(iarr, count)
    assert len(iarr) == count

def test_generator(count):
    iarr = array.array('i', (0 for _ in xrange(count)))
    assert len(iarr) == count

def test_list(count):
    L = [0]*count
    assert len(L) == count

if __name__ == '__main__':
    import timeit
    c = 100000
    n = 10
    print timeit.Timer("test(c)", "from __main__ import c, test_zerofill as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_generator as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_list as test").repeat(number=n)

Results: 结果:

(array in blocks) [0.022809982299804688, 0.014942169189453125, 0.014089107513427734]
(array with generator) [1.1884641647338867, 1.1728270053863525, 1.1622772216796875]
(list) [0.023866891860961914, 0.035660028457641602, 0.023386955261230469]
import numpy as np

new_array=np.linspace(0,10,11).astype('int')

An alternative for casting the type when the array is made. 在制作阵列时转换类型的替代方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM