Home >Backend Development >Python Tutorial >How to create an array in python

How to create an array in python

藏色散人
藏色散人Original
2019-06-24 13:31:2653389browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn