如何使用 Python Append() 命令在列表中添加項目

我們有一個數字或字符串列表,我們想將項目附加到列表中。 基本上,我們可以使用 append 方法來實現我們想要的。

append() 方法將單個項目添加到現有列表中。 它不會返回一個新列表; 而是修改原始列表。

的語法 append() 方法

list.append(item)

append() 參數

append() 方法接受單個項目並將其添加到列表的末尾。 該項目可以是數字、字符串、另一個列表、字典等。

1) 向列表中添加元素

讓我們看看將元素添加到列表中 example

# fruit list
fruit = ['orange', 'apple', 'banana']

# an element is added
fruit.append('pineapple')

#Updated Fruit List
print('Updated fruit list: ', fruit)

output
Updated fruit list: ['orange', 'apple', 'banana', 'pineapple']

如你所見 , 'pineapple' 元素已添加為最後一個元素。

2)將列表添加到列表中

讓我們看看如何將列表添加到列表中

# fruit list
fruit = ['orange', 'apple', 'banana']

# another list of green fruit
green_fruit = ['green apple', 'watermelon']

# adding green_fruit list to fruit list
fruit.append(green_fruit)

#Updated List
print('Updated fruit list: ', fruit)

output
Updated fruit list: ['orange', 'apple', 'banana', ['green apple', 'watermelon']]

正如您在將 green_fruit 列表附加到水果列表時所看到的那樣,它作為一個列表而不是兩個元素。

3) 將列表的元素添加到列表中

這裡我們將使用 extend() 將列表元素添加到另一個列表的方法,我們將使用相同的先前 example 看到差異。

# fruit list
fruit = ['orange', 'apple', 'banana']

# another list of green fruit
green_fruit = ['green apple', 'watermelon']

# adding green_fruit list to fruit list
fruit.extend(green_fruit)

#Updated List
print('Updated animal list: ', fruit)

output
Updated fruit list: ['orange', 'apple', 'banana', 'green apple', 'watermelon']

正如我們所見,green_fruit 列表已作為元素添加到水果列表中,而不是作為列表添加。

4) 使用 for 循環將元素添加到列表中

我們將使用 For loop 將元素組附加到列表中。

# numbers list
numbers = []

# use for loop to fill numbers list with elements
for i in range(10):
numbers.append(i)

#Updated List
print('Updated numbers list: ', numbers)

output
Updated numbers list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我們做了空清單 numbers 並用於循環以追加 0 到 9 範圍內的數字,因此在第一次工作中 for 循環追加 0 並檢查範圍內的數字 2,如果在範圍內追加它,依此類推直到達到數字 9,添加它和 for 循環停止工作。

5)使用while循環將元素添加到列表中

我們將使用 While loop 將元素組附加到列表中。

# temperature list
temperature = []

# use while loop to fill temperature list with temperature degrees
degree_value = 20
degree_max = 50
while degree_value <= degree_max:
temperature.append(degree_value)
degree_value += 5

#Updated Temperature List
print('Updated temperature list: ', temperature)

output
Updated temperature list: [20, 25, 30, 35, 40, 45, 50]

我們做了空清單 temperature 並放置起點 degree_value 和極限點 degree_max 並說,當 degree_value 小於或等於 degree_max 時,將此值附加到溫度列表中,然後將 degree_value 的值增加 5 度,while 循環將工作直到 degree_value 等於 degree_max 並停止工作。

6) 使用 numpy 模塊附加兩個數組

我們將使用 append 方法在 numpy 附加兩個數組的模塊。

# import numpy module
import numpy as np

A = np.array([3])
B = np.array([1,5,5])
C = np.append(A, B)

#print array C
print('Array C: ', C)

output
Array C: [3 1 5 5]

注意:你應該安裝 numpy 模塊首先通過此命令 $ pip3 install numpy.

結論

在本文中,我們學習瞭如何使用 Python append() 命令在列表中添加項目。 請讓我知道,如果你有任何問題。

另請閱讀:

  • 如何使用 Python Sort List() 方法對列表進行排序