Home > Article > Backend Development > How to create an array in python
Direct definition method:
1. Direct definition
matrix=[0,1,2,3]
2. Indirect definition
matrix=[0 for i in range(4)] print(matrix)
Two Numpy methods:
Numpy has a built-in function to create an array from scratch:
zeros(shape) will create an array with the specified shape. 0-filled array. The default dtype is float64.
The following are several commonly used creation methods:
#coding=utf-8import numpy as np a = np.array([1,2,3,4,5])print a b = np.zeros((2,3))print b c = np.arange(10)print c d = np.arange(2,10,dtype=np.float)print d e = np.linspace(1.0,4.0,6)print e f = np.indices((3,3))print f
Three other conversion methods:
There is also a more commonly used method for arrays, which is Convert from other Python structures (e.g., lists, tuples).
Some examples are given below.
Convert list to array:
a = [] a.append((1,2,4)) a.append((2,3,4)) a = np.array(a) a.flatten()
Convert tuple to array:
import numpy as np mylist = [1,2,3]print tuple(mylist) iarray = np.array(tuple(mylist))print iarray
Related recommendations: "Python Tutorial"
The above is the detailed content of How to create an array in python. For more information, please follow other related articles on the PHP Chinese website!