How to create a fix size list in python?

后端 未结 9 1778
不思量自难忘°
不思量自难忘° 2020-12-04 20:53

In C++, I can create a array like...

int* a = new int[10];

in python,I just know that I can declare a list,than append some items,or like..

9条回答
  •  一整个雨季
    2020-12-04 21:26

    You can do it using array module. array module is part of python standard library:

    from array import array
    from itertools import repeat
    
    a = array("i", repeat(0, 10))
    # or
    a = array("i", [0]*10)
    

    repeat function repeats 0 value 10 times. It's more memory efficient than [0]*10, since it doesn't allocate memory, but repeats returning the same number x number of times.

提交回复
热议问题