您好,欢迎访问一九零五行业门户网

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 用作数组,因此可以使用 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 arrayint_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 arrayarray = 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]
这里原始数组保持不变,结果数组已使用新元素更新。
以上就是python程序将一个元素添加到数组中的详细内容。
其它类似信息

推荐信息