如何使用Python Append()命令在列表中添加项目
我们有一个数字或者字符串列表,我们想将项目追加到列表中。
基本上,我们可以使用“追加”方法来实现所需的功能。
'append()'方法将单个项目添加到现有列表中。
它不会返回新列表。
而是修改原始列表。
'append()'方法的语法
list.append(item)
append()参数
'append()'方法采用单个项目并将其添加到列表的末尾。
该项目可以是数字,字符串,另一个列表,字典等。
1)将元素添加到列表
让我们看一个例子,向列表中添加元素
# 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']
如我们所见,“菠萝”元素已添加为最后一个元素。
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()'方法将list的元素添加到另一个列表中,我们将使用相同的示例查看差异。
# 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循环”将元素组追加到列表中。
# 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]
我们制作了一个空列表“数字”,并用于循环以在0到9的范围内添加数字,因此对于循环工作在第一个工作中添加0并检查是否在范围内的2,如果在范围内则以此类推,直到达到数字9 ,它添加了它,并且for循环停止工作。
5)使用while循环将元素添加到列表中
我们将使用“ While循环”将元素组追加到列表中。
# 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]
我们制作了一个空列表“温度”,并放置了起点“ degree_value”和极限点“ degree_max”,然后说,当degree_value小于或者等于degree_max时,将此值添加到温度列表中,然后将degree_value的值增加5度,而while循环将一直工作到degree_value等于degree_max并停止工作。
6)使用numpy模块添加两个数组
我们将在“ numpy”模块中使用“ append”方法来添加两个数组。
# 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]
注意:我们应该首先通过此命令'$pip3 install numpy'安装'numpy'模块。
总结
在本文中,我们学习了如何使用Python append()命令在列表中添加项目。
请让我知道,如果你有任何问题。
另请阅读:
- 如何使用Python Sort List()方法对列表进行排序