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

How to use append in python

angryTom
angryTomOriginal
2019-07-23 15:06:1987219browse

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)

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

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

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)

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]]

Matrix transpose function transpose method:

a=np.transpose(a)

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]])

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))

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]]

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!

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
Previous article:Function of str functionNext article:Function of str function