Python 简明教程

Python - Add Array Items

Python 数组是一个可变序列,这意味着它们可以在需要时被更改或修改。但是,可以将相同数据类型的数据添加到数组中。以类似的方式,您只能连接两个相同数据类型数组。

Python array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.

Adding Elements to Python Array

可以在 Python 中以多种方式向数组添加元素 −

There are multiple ways to add elements to an array in Python −

  1. Using append() method

  2. Using insert() method

  3. Using extend() method

Using append() method

要在 array 中添加新元素,请使用 append() 方法。它接受单个项作为参数,并将其追加到指定数组的末尾。

To add a new element to an array, use the append() method. It accepts a single item as an argument and append it at the end of given array.

Syntax

append() 方法的语法如下 −

Syntax of the append() method is as follows −

append(v)

其中,

Where,

  1. v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

Example

在这里,我们使用 append() 方法在指定数组的末尾添加元素。

Here, we are adding element at the end of specified array using append() method.

import array as arr
a = arr.array('i', [1, 2, 3])
a.append(10)
print (a)

它将生成以下 output

It will produce the following output

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

Using insert() method

可以通过 insert() 方法在指定索引处添加一个新元素。Python 中的数组模块定义了此方法。它接受两个参数,分别是索引和值,并在添加指定值后返回一个新数组。

It is possible to add a new element at the specified index using the insert() method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.

Syntax

此方法的语法如下 −

Syntax of this method is shown below −

insert(i, v)

其中,

Where,

  1. i − The index at which new value is to be inserted.

  2. v − The value to be inserted. Must be of the arraytype.

Example

以下示例演示如何借助 insert() 方法在特定索引处添加数组元素。

The following example shows how to add array elements at specific index with the help of insert() method.

import array as arr
a = arr.array('i', [1, 2, 3])
a.insert(1,20)
print (a)

它将生成以下 output

It will produce the following output

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

Using extend() method

extend() 方法属于 Python 数组模块。它用于从同一种数据类型的可迭代项或数组中添加所有元素。

The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.

Syntax

此方法具有以下语法 −

This method has the following syntax −

extend(x)

其中,

Where,

  1. x − This parameter specifies an array or iterable.

Example

在此示例中,我们向指定数组中添加数组中的项目。

In this example, we are adding items from another array to the specified array.

import array as arr
a = arr.array('i', [1, 2, 3, 4, 5])
b = arr.array('i', [6,7,8,9,10])
a.extend(b)
print (a)

在执行以上代码时,将生成以下内容 output

On executing the above code, it will produce the following output

array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])