📜  Python - 初始化给定长度的空数组

📅  最后修改于: 2022-05-13 01:54:39.198000             🧑  作者: Mango

Python - 初始化给定长度的空数组

先决条件: Python中的列表

我们知道 Array 是存储在连续内存位置的项目的集合。在Python中,可以将 List(动态数组)视为 Array。在本文中,我们将学习如何初始化一个给定大小的空数组。

让我们看看执行此任务的不同 Pythonic 方式。

方法 1 –

句法:

list1 = [0] * size
list2 = [None] * size
# initializes all the 10 spaces with 0’s
a = [0] * 10 
  
# initializes all the 10 spaces with None
b = [None] * 10 
  
# initializes all the 10 spaces with A's
c = ['A'] * 5 
  
# empty list which is not null, it's just empty.
d = [] 
  
print (a, "\n", b, "\n", c, "\n", d);
输出:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
[None, None, None, None, None, None, None, None, None, None] 
['A', 'A', 'A', 'A', 'A'] 
[]


方法 2 –像 C 一样使用循环并分配大小。

句法:

a = [0 for x in range(size)] #using loops
a = []
b = []
  
# initialize the spaces with 0’s with 
# the help of list comprehensions
a = [0 for x in range(10)]
print(a)
  
# initialize multi-array 
b = [ [ None for y in range( 2 ) ]
             for x in range( 2 ) ]
               
print(b)
输出:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[[None, None], [None, None]]


方法 3 –使用 Numpy 创建空数组。

import numpy
  
# create a simple array with numpy empty()
a = numpy.empty(5, dtype=object)
print(a)
  
# create multi-dim array by providing shape
matrix = numpy.empty(shape=(2,5),dtype='object')
print(matrix)

输出:

[None None None None None]

[[None None None None None]
 [None None None None None]]