How do I get an empty array of any size in python?

后端 未结 8 1705
你的背包
你的背包 2020-12-04 10:57

I basically want a python equivalent of this in C:

int a[x];

but in python I declare an array like:

a = []
<
相关标签:
8条回答
  • 2020-12-04 11:13

    You can use numpy:

    import numpy as np
    

    Example from Empty Array:

    np.empty([2, 2])
    array([[ -9.74499359e+001,   6.69583040e-309],
           [  2.13182611e-314,   3.06959433e-309]])  
    
    0 讨论(0)
  • 2020-12-04 11:20

    If you actually want a C-style array

    import array
    a = array.array('i', x * [0])
    a[3] = 5
    try:
       [5] = 'a'
    except TypeError:
       print('integers only allowed')
    

    Note that there's no concept of un-initialized variable in python. A variable is a name that is bound to a value, so that value must have something. In the example above the array is initialized with zeros.

    However, this is uncommon in python, unless you actually need it for low-level stuff. In most cases, you are better-off using an empty list or empty numpy array, as other answers suggest.

    0 讨论(0)
提交回复
热议问题