Home > Backend Development > Python Tutorial > How to use append in python

How to use append in python

angryTom
Release: 2019-07-23 15:06:19
Original
87226 people have browsed it

How to use append in python

Recommended tutorial: Python tutorial

append() function

Description: Add an element object at the end (end) of the list ls

Syntax: ls.append(object) -> None No return value

Example:

a=[1,2,3]
a.append(5)
Copy after login

At this time, the running result is [1, 2, 3, 5]

a=[1,2,3]
a.append([5])
Copy after login

At this time, running The result is [1, 2, 3, [5]]

The result is no longer an array, but a list

Use append to generate a multi-dimensional array:

import numpy as np
a=[] 
for i in range(5): 
    a.append([])
    for j in range(5): 
        a[i].append(i)
Copy after login

The results are as follows:

[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]
Copy after login

Matrix transpose function transpose method:

a=np.transpose(a)
Copy after login

The results are as follows:

  ([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
Copy after login

Array merge operation :

h=np.arange(-2,2,1)
h.shape
k1=np.c_[h,h] #横向合并函数1 np.c_,将数组转化为列向量
k2=np.hstack((h,h)) #横向合并函数2 np.hstack,将数组作为横向量
print("k1="+str(k1))
print("k2="+str(k2))
l1=np.r_[[h],[h]] #纵向合并函数np.r_
l2=np.vstack((h,h)) #纵向合并函数np.vstack
print("l1="+str(l1))
print("l2="+str(l2))
Copy after login

The results are as follows:

k1=[[-2 -2]
 [-1 -1]
 [ 0  0]
 [ 1  1]]
k2=[-2 -1  0  1 -2 -1  0  1]
l1=[[-2 -1  0  1]
 [-2 -1  0  1]]
l2=[[-2 -1  0  1]
 [-2 -1  0  1]]
Copy after login

The above is the detailed content of How to use append 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