Python – 列表合并



在 Python 中合并列表

Python 中合并列表是指将多个列表的元素组合成单个列表。这可以通过多种方法实现,例如串联、列表推导式或使用内置函数如 `extend()` 或 `+` 运算符。

合并列表不会修改原始列表,而是创建一个包含合并元素的新列表。

使用连接运算符合并列表

Python 中的连接运算符,用+表示,用于将两个序列(例如字符串、列表或元组)连接成单个序列。当应用于列表时,连接运算符会将两个(或多个)列表的元素连接起来,创建一个包含两个列表所有元素的新列表。

我们可以通过简单地使用+符号连接列表来合并列表。

示例

在下面的示例中,我们正在连接两个列表“L1”和“L2”的元素,创建一个新的列表“joined_list”,其中包含两个列表的所有元素:

# Two lists to be joined
L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
# Joining the lists
joined_list = L1 + L2

# Printing the joined list
print("Joined List:", joined_list)

以上代码的输出如下:

Joined List: [10, 20, 30, 40, 'one', 'two', 'three', 'four']

使用列表推导式合并列表

列表推导式是创建 Python 列表的一种简洁方法。它用于通过对现有可迭代对象(例如列表、元组或范围)中的每个项目应用表达式来生成新的列表。列表推导式的语法如下:

new_list = [expression for item in iterable]

这将创建一个新列表,其中表达式针对可迭代对象中的每个项目进行计算。

我们可以通过迭代多个列表并将它们的元素附加到新列表中来使用列表推导式合并列表。

示例

在这个例子中,我们使用列表推导式将两个列表 L1 和 L2 合并成一个列表。结果列表 joined_list 包含 L1 和 L2 的所有元素:

# Two lists to be joined
L1 = [36, 24, 3]
L2 = [84, 5, 81]
# Joining the lists using list comprehension
joined_list = [item for sublist in [L1, L2] for item in sublist]
# Printing the joined list
print("Joined List:", joined_list)

以上代码的输出如下:

Joined List: [36, 24, 3, 84, 5, 81]

使用 append() 函数合并列表

Python 中的 `append()` 函数用于向列表的末尾添加单个元素。此函数通过将元素添加到列表的末尾来修改原始列表。

我们可以通过迭代一个列表的元素并将每个元素附加到另一个列表来使用 `append()` 函数合并列表。

示例

在下面的示例中,我们使用 `append()` 函数将“list2”中的元素附加到“list1”。我们通过迭代“list2”并将每个元素添加到“list1”来实现此目的:

# List to which elements will be appended
list1 = ['Fruit', 'Number', 'Animal']
# List from which elements will be appended
list2 = ['Apple', 5, 'Dog']
# Joining the lists using the append() function
for element in list2:
    list1.append(element)
# Printing the joined list
print("Joined List:", list1)

我们得到如下所示的输出:

Joined List: ['Fruit', 'Number', 'Animal', 'Apple', 5, 'Dog']

使用 extend() 函数合并列表

Python 的 `extend()` 函数用于将可迭代对象(例如另一个列表)中的元素附加到列表的末尾。此函数就地修改原始列表,将可迭代对象的元素添加到列表的末尾。

我们可以通过在一个列表上调用 `extend()` 函数并将另一个列表(或任何可迭代对象)作为参数来使用它合并列表。这会将第二个列表中的所有元素附加到第一个列表的末尾。

示例

在下面的示例中,我们使用 `extend()` 函数通过将“list2”的元素附加到“list1”来扩展“list1”:

# List to be extended
list1 = [10, 15, 20]
# List to be added
list2 = [25, 30, 35]
# Joining the lists using the extend() function
list1.extend(list2)
# Printing the extended list
print("Extended List:", list1)

获得的输出如下所示:

Extended List: [10, 15, 20, 25, 30, 35]
广告
© . All rights reserved.