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

后端 未结 8 1704
你的背包
你的背包 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:05
    x=[]
    for i in range(0,5):
        x.append(i)
        print(x[i])
    
    0 讨论(0)
  • 2020-12-04 11:06

    You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).

    But, try this:

    a = [0 for x in range(N)]  # N = size of list you want
    a[i] = 5  # as long as i < N, you're okay
    

    For lists of other types, use something besides 0. None is often a good choice as well.

    0 讨论(0)
  • 2020-12-04 11:07

    Just declare the list and append each element. For ex:

    a = []
    a.append('first item')
    a.append('second item')
    
    0 讨论(0)
  • 2020-12-04 11:08

    If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:

    # cast() is available starting Python 3.3
    size = 10**6 
    ints = memoryview(bytearray(size)).cast('i') 
    
    ints.contiguous, ints.itemsize, ints.shape
    # (True, 4, (250000,))
    
    ints[0]
    # 0
    
    ints[0] = 16
    ints[0]
    # 16
    
    0 讨论(0)
  • 2020-12-04 11:10

    also you can extend that with extend method of list.

    a= []
    a.extend([None]*10)
    a.extend([None]*20)
    
    0 讨论(0)
  • 2020-12-04 11:11

    If by "array" you actually mean a Python list, you can use

    a = [0] * 10
    

    or

    a = [None] * 10
    
    0 讨论(0)
提交回复
热议问题