Python 简明教程

Python - Remove Array Items

Removing array items in Python

Python 陣列是一個可變動序列,這表示可以輕鬆進行類似新增新元素和移除現有元素等運算。可以透過指定值或指定陣列中的位置來從陣列中移除元素。

Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

array 模組定義了兩個方法,分別是 remove() 和 pop()。remove() 方法會依據值移除元素,而 pop() 方法會依據位置移除陣列項目。

The array module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

Remove First Occurrence

若要從陣列中移除給定值的第一次出現,請使用 remove() 方法。此方法會接收元素,並在陣列中找到此元素時將其移除。

To remove the first occurrence of a given value from the array, use remove() method. This method accepts an element and removes it if the element is available in the array.

Syntax

array.remove(v)

其中, v 是要從陣列中移除的值。

Where, v is the value to be removed from the array.

Example

以下範例示範如何使用 remove() 方法。在這裡,會從指定的陣列中移除一個元素。

The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

import array as arr

# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])

# before removing array
print ("Before removing:", numericArray)
# removing array
numericArray.remove(311)
# after removing array
print ("After removing:", numericArray)

它将生成以下 output

It will produce the following output

Before removing: array('i', [111, 211, 311, 411, 511])
After removing: array('i', [111, 211, 411, 511])

Remove Items from Specific Indices

若要從特定索引移除陣列元素,請使用 pop() 方法。此方法會從陣列中移除指定索引的元素,並於移除後傳回第 i 個位置的元素。

To remove an array element from specific index, use the pop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

Syntax

array.pop(i)

i 是要删除元素的索引。

Where, i is the index for the element to be removed.

Example

在此示例中,我们将了解如何使用 pop() 方法从数组中删除元素。

In this example, we will see how to use pop() method to remove elements from an array.

import array as arr

# creating array
numericArray = arr.array('i', [111, 211, 311, 411, 511])

# before removing array
print ("Before removing:", numericArray)
# removing array
numericArray.pop(3)
# after removing array
print ("After removing:", numericArray)

它将生成以下 output

It will produce the following output

Before removing: array('i', [111, 211, 311, 411, 511])
After removing: array('i', [111, 211, 311, 511])