Python 向数组添加元素

Python 向数组添加元素

数组是一组具有相同数据类型的元素,数组中的每个元素都由索引值唯一标识。它是一种最简单的数据结构,我们可以很容易地添加或删除元素。

Python中的数组

Python没有特定的数据结构来表示数组。在这里,我们可以使用 列表 作为数组。

[9, 3, 1, 6, 9]

我们可以使用数组或NumPy模块来在Python中处理数组。

array('i', [1, 2, 3, 4])

上面的数组是 整数数组 它是由数组模块定义的。

同样地,我们也可以使用NumPy模块来定义一个NumPy数组。

array([1, 2, 3, 4])

在Python中,索引从0开始。上述所有数组的元素也从0、1、…、(n-1)进行索引。

输入输出场景

假设我们有一个包含整数值的输入数组。并且结果数组将附加一个元素。

Input array:
A = [1, 5, 3, 6]
Output array:
[1, 5, 3, 6, 2]

给定数组的末尾添加了整数元素2。

在下面的文章中,我们可以看到多种在Python中向数组添加元素的方法。

使用列表数据结构

由于我们使用列表作为数组,我们可以使用list.append()方法将元素添加到数组中。

语法

list.append(element)

它将一个元素添加到列表的末尾。等效于 a[len(a):] = [x]。

例子

lst = [1, 2, 3, 4, 5, 6] 
print ("The original array is: ",lst) 
print() 

# append an element 
lst.append(9)
print ("The resultant array is: ",lst)

结果

The original array is:  [1, 2, 3, 4, 5, 6]

The resultant array is:  [1, 2, 3, 4, 5, 6, 9]

元素9被添加到数组中,被添加到数组的末尾。

使用数组模块

Python中的数组模块允许我们创建一个数组,并且可以紧凑地表示一个数组。要使用数组模块,我们首先需要导入数组模块。

语法

array.append(x)

将一个新的值为x的项追加到数组的末尾。

示例

import array

# creating array
int_array = array.array('i', [1, 2, 3, 4])
print ("The original array is: ",int_array) 
print() 

# append an element 
int_array.append(0)
print ("The resultant array is: ",int_array)

输出

The original array is:  array('i', [1, 2, 3, 4])

The resultant array is:  array('i', [1, 2, 3, 4, 0])

整数类型在创建int_array对象时指定。如果我们尝试将任何其他类型的元素附加到数组对象,则会引发如下错误。

TypeError − 预期为整数参数,得到浮点数

使用NumPy模块

通过使用numpy库,我们可以使用numpy.array()方法轻松创建一个数组。同样地,我们也可以使用numpy.append()方法向数组附加一个元素。

语法

numpy.append(array, element)

该方法将一个元素添加到数组的末尾。它创建一个新数组,该数组可以是旧数组的副本,并且带有添加的元素,以便原始数组保持不变。

示例

在此示例中,我们将使用for循环迭代字符串数组元素。

import numpy

# creating array
array = numpy.array([1, 2, 3, 4])
print ("The original array is: ", array) 
print() 

# append an element 
result = numpy.append(array, 9)
print ("The resultant array is: ", result)

输出

The original array is:  [1 2 3 4]

The resultant array is:  [1 2 3 4 9]

原始数组仍然保持不变,而结果数组则根据新元素进行了更新。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程