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]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
使用 map() 和 add()
我们可以结合使用 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]
广告