如何在 Python 中添加两个列表

2025年3月17日 | 阅读 7 分钟

在本主题中,我们将学习如何在 Python 中添加两个列表。但在深入学习主题之前,我们需要理解 Python 中的列表一词。Python 列表用于在变量中存储多个项目。列表中的项目可以是任何有序的、可变的,并且允许存储重复值。列表中的每个项目都有一个相应的索引值,列表的第一个索引从 {0} 开始,列表的长度索引必须是 n-1。列表中的每个项目都由逗号 (,) 分隔,并用方括号 [] 括起来。

How to add two lists in Python

语法

这里 L1 和 L2 是两个包含相同或不同数据类型元素的列表。列表 L1 包含整数字符串数据类型元素,而列表 L2 只包含整数数据类型元素。

让我们看一个在 Python 中打印列表的程序。

programList.py

输出

Display the List1 ['Rose', 'Lotus', 24, 'Gold', 'USA']
Display the List2 [1, 2, 4, 5, 6]
Display the Department List ['Web Designing', 40, 20]
Display the CS Department [58, 'Ms Wiley']

让我们讨论在 Python 程序中添加两个列表的各种方法。

方法 1:使用朴素方法添加两个列表

这是一种简单的方法,它使用循环append方法在 Python 中添加两个列表,并将列表的总和添加到第三个列表中。for 循环对具有相同索引号的两个列表执行加法,并持续迭代元素直到列表末尾。之后,append 方法将添加的元素插入到第三个列表中。

让我们看一个使用朴素方法在 Python 中添加两个列表的程序。

naivePro.py

输出

Python Original list 1: [5, 10, 15, 20, 25, 30]
Python Original list 2: [2, 4, 6, 8, 10, 12]
 Addition of the list lt1 and lt2 is: [7, 14, 21, 28, 35, 42]

方法 2:使用列表推导式添加两个列表

这是 Python 中朴素方法的简写技术。推导式技术输入更快,并且可以检索两个列表的总和。因此,它在 Python 编程中用于执行此类任务。

让我们看一个使用朴素方法在 Python 中添加两个列表的程序。

comprehension.py

输出

Python list 1 : [2, 4, 6, 8, 10, 30]
Python list 2 : [2, 4, 6, 8, 10, 12]
 Addition of the list lt1 and lt2 is: [4, 8, 12, 16, 20, 42]

方法 3:使用带加法运算符的 map() 函数在 Python 中添加两个列表

在 Python 中,map() 函数用于通过传递列表变量 (lt1, lt2) 并将其作为参数来添加两个列表。在 map() 函数内部,加法参数充当加法运算符来添加列表并返回总和。

考虑一个使用带加法运算符的 map() 函数在 Python 中添加两个列表的程序。

AddMap.py

输出

Display the elements of List 1 [4, 8, 12, 16, 20, 24]
Display the elements of List 2 [2, 4, 6, 8, 10, 12]
 Sum of the list 1 and list 2 is: [6, 12, 18, 24, 30, 36]

方法 4:从用户那里接受列表元素并连接两个列表。

在此程序中,我们输入用户的列表元素,并通过For 循环将它们插入到列表中。之后,在 Python 程序中执行两个列表的加法。

让我们看一个从用户那里获取输入列表元素并对其进行相加的程序。

Accept.py

输出

Enter the total number of the list elements: 5
 Enter the items into the List 1:
 Enter the value of 1 index is: 3
 Enter the value of 2 index is: 6
 Enter the value of 3 index is: 9
 Enter the value of 4 index is: 12
 Enter the value of 5 index is: 15
 Enter the items into the List 2:
 Enter the value of 1 index is: 2
 Enter the value of 2 index is: 4
 Enter the value of 3 index is: 6
 Enter the value of 4 index is: 8
 Enter the value of 5 index is: 10

 The addition of the two list is [5, 10, 15, 20, 25]

方法 5:使用带 sum() 函数的 zip() 函数添加两个列表

sum() 函数用于使用 zip() 函数分组的列表元素的索引号来添加两个列表。zip() 函数在 sum() 函数中使用,通过按索引分组的列表来分组列表元素。

让我们看一个在 Python 中使用 zip 函数和 sum 函数添加列表元素的程序。

zipSum.py

输出

Display the elements of List 1 [6, 12, 18, 3, 6, 9]
Display the elements of List 2 [4, 8, 12, 2, 4, 6]
 Sum of the list 1 and list 2 is : [10, 20, 30, 5, 10, 15]