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

How to create an array in python

藏色散人
Release: 2019-06-24 13:31:42
Original
53392 people have browsed it

How to create an array in python

Direct definition method:

1. Direct definition

  matrix=[0,1,2,3]
Copy after login

2. Indirect definition

  matrix=[0 for i in range(4)]  print(matrix)
Copy after login

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
Copy after login

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()
Copy after login

Convert tuple to array:

import numpy as np
mylist = [1,2,3]print tuple(mylist)
iarray = np.array(tuple(mylist))print iarray
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template