How to create an integer array in Python?

前端 未结 8 712
旧巷少年郎
旧巷少年郎 2020-12-24 01:11

It should not be so hard. I mean in C,

int a[10]; 

is all you need. How to create an array of all zeros for a random size. I know the zero

8条回答
  •  再見小時候
    2020-12-24 01:44

    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 - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

    The second parameter to array.array is a generator, which constructs the defined sequence as it is read. 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! :)

提交回复
热议问题