添加两个Python列表元素

可以在python中添加列表,从而创建一个包含两个列表中的元素的新列表。有两种添加两个列表的方法,下面将对其进行描述。但是在所有这些情况下,列表的长度必须相同。

使用 Append()

使用append()我们可以将一个列表的元素添加到另一个列表。

示例

List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
# printing original lists
print ("list1 : " + str(List1))
print ("list2 : " + str(List2))
newList = []
for n in range(0, len(List1)):
   newList.append(List1[n] + List2[n])
print(newList)

运行上面的代码将为我们提供以下结果:

list1 : [7, 5.7, 21, 18, 2.6666666666666665]
list2 : [9, 15, 6.2, 0.3333333333333333, 11]
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]

使用Map()Add()

我们可以起诉map()与一起add()添加列表中的元素。映射函数使用添加函数的第一个参数,并将两个索引相同的列表的元素相加。

示例

from operator import add
#Adding two elements in the list.
List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
# printing original lists
print ("list1 : " + str(List1))
print ("list2 : " + str(List2))
NewList = list(map(add,List1,List2))
print(NewList)

运行上面的代码将为我们提供以下结果:

list1 : [7, 5.7, 21, 18, 2.6666666666666665]
list2 : [9, 15, 6.2, 0.3333333333333333, 11]
[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]

使用ZIp()Sum()

在类似的方法和上面我们可以采取zip()sum()使用for循环。通过for循环,我们将列表的两个元素绑定到同一索引,然后将其sum()应用于每个元素。

示例

#Adding two elements in the list.
List1 = [7, 5.7, 21, 18, 8/3]
List2 = [9, 15, 6.2, 1/3,11]
result = [sum(n) for n in zip(List1, List2)]
print(result)

运行上面的代码将为我们提供以下结果:

[16, 20.7, 27.2, 18.333333333333332, 13.666666666666666]