优草派  >   Python

python怎么合并list?

孙慧敏            来源:优草派

要将多个list合并成一个list,通常使用extend()方法,也可以使用+操作符或list类中的extend()方法,本文将介绍这些方法的使用。

python怎么合并list?

Python中list类提供了extend()方法用于向列表追加另一个列表中的元素。

例如:

```

>>> list1 = [1,2,3]

>>> list2 = [4,5,6]

>>> list1.extend(list2)

>>> print(list1)

[1, 2, 3, 4, 5, 6]

```

此外,也可以使用+操作符将两个列表合并成一个列表

例如:

```

>>> list1 = [1,2,3]

>>> list2 = [4,5,6]

>>> list3 = list1 + list2

>>> print(list3)

[1, 2, 3, 4, 5, 6]

```

还可以使用以下方式合并多个列表:

```

>>> list1 = [1,2,3]

>>> list2 = [4,5,6]

>>> list3 = [7,8,9]

>>> combined_list = []

>>> combined_list.extend(list1)

>>> combined_list.extend(list2)

>>> combined_list.extend(list3)

>>> print(combined_list)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

```

除了以上方法,还可以使用for循环的方式实现列表合并:

```

>>> list1 = [1,2,3]

>>> list2 = [4,5,6]

>>> list3 = [7,8,9]

>>> combined_list = []

>>> for lst in [list1, list2, list3]:

... combined_list.extend(lst)

>>> print(combined_list)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

```

从上述方式可以看出,extend()方法可以追加另一个列表中的所有元素,而+号操作符只是将两个列表合并成一个新的列表,但不会修改原始列表。

同时,如果你需要将多个列表中的元素去重后合并成一个列表,则可以使用Python的内置函数set()实现,具体代码如下:

```

>>> list1 = [1,2,3]

>>> list2 = [3,4,5]

>>> list3 = [5,6,7]

>>> combined_list = list(set(list1 + list2 + list3))

>>> print(combined_list)

[1, 2, 3, 4, 5, 6, 7]

```

现在你已经学会了多种方法用于合并多个列表,希望你能在实际应用中灵活运用,提高工作效率。

【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。
TOP 10
  • 周排行
  • 月排行