引言
在日常編程工作中,列表操作是非常常見的操作。而對於多個列表的合併,我們需要重點關注合併的方法。
正文
從兩個列表合併
最常見的列表合併就是從兩個列表合併。在Python中,可以使用extend()方法或者”+”運算符,將兩個列表合併。代碼如下:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = list1 + list2 list4 = list1.extend(list2) print(list3) #[1, 2, 3, 4, 5, 6] print(list4) #[1, 2, 3, 4, 5, 6]
上面的代碼,我們可以看到使用”+”運算符和extend()方法可以實現將兩個列表合併的效果。
列表合併成一個列表
有時候,我們需要將多個列表合併成一個列表。在Python中,我們可以使用list的extend()方法,將多個列表合併為一個列表。例如:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] list1.extend(list2) list1.extend(list3) print(list1) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
在上面的代碼中,我們可以看到,通過extend()方法來合併多個列表成為一個列表。
列表的合併與排序
在某些場景下,我們需要將兩個列表合併,並且對合併後的列表進行排序。在Python中,可以使用sort()方法來實現。例如:
list1 = [4, 1, 3] list2 = [2, 5, 6] list3 = list1 + list2 list3.sort() print(list3) #[1, 2, 3, 4, 5, 6]
在上面的代碼中,我們首先將兩個列表合併,然後使用sort()方法對合併後的列表進行排序。
將兩個列表合併的方法
在Python中,有多種方法可以將兩個列表合併。除了前面提到過的”+”運算符和extend()方法之外,還有使用列表解析和使用*運算符。例如:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [i for i in list1] + [i for i in list2] list4 = [*list1, *list2] print(list3) #[1, 2, 3, 4, 5, 6] print(list4) #[1, 2, 3, 4, 5, 6]
在上面的代碼中,我們使用列表解析和*運算符,將兩個列表合併為一個新的列表。
合併列表的方法
除了將兩個列表合併外,有時候我們還需要合併多個列表。Python提供了多種方法來實現這個目的,包括使用列表解析、使用reduce()函數和使用numpy包。例如:
# 使用列表解析 list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] list4 = [i for sublist in [list1, list2, list3] for i in sublist] print(list4) #[1, 2, 3, 4, 5, 6, 7, 8, 9] # 使用reduce()函數 from functools import reduce lists = [list1, list2, list3] list4 = reduce(lambda x, y: x+y, lists) print(list4) #[1, 2, 3, 4, 5, 6, 7, 8, 9] # 使用numpy包 import numpy as np lists = [list1, list2, list3] list4 = np.concatenate(lists) print(list4) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
在上面的代碼中,我們可以看到,使用列表解析、reduce()函數和numpy包都可以實現多個列表的合併。
將兩個列表合併成一個列表的方法
有時候,我們需要將兩個列表合併成一個列表,而且不能使用extend()方法或者”+”運算符。在Python中,可以使用append()方法或者map()函數來實現。例如:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [] for i in list1: list3.append(i) for i in list2: list3.append(i) print(list3) #[1, 2, 3, 4, 5, 6] list4 = list(map(lambda x: x, list1)) + list(map(lambda x: x, list2)) print(list4) #[1, 2, 3, 4, 5, 6]
在上面的代碼中,我們可以看到,使用append()方法和map()函數都可以將兩個列表合併成一個新的列表。
多個列表合併
除了兩個列表的合併外,有時候我們需要合併多個列表。除了前面提到過的使用列表解析和reduce()函數,還有一個使用chain()函數的方法。例如:
from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] list4 = list(chain(list1, list2, list3)) print(list4) #[1, 2, 3, 4, 5, 6, 7, 8, 9]
在上面的代碼中,我們可以看到,使用chain()函數可以將多個列表進行合併。
將兩個列表的內容合併的方法是
在Python中,可以使用zip()函數將兩個列表的內容合併。例如:
list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = list(zip(list1, list2)) print(list3) #[(1, 4), (2, 5), (3, 6)]
在上面的代碼中,我們可以看到,使用zip()函數可以將兩個列表的內容合併為一個元組。
小結
本文從多個方面對列表合併方法進行了詳細的闡述。我們從從兩個列表合併、列表合併為一個列表、列表的合併與排序、將兩個列表合併的方法、合併列表的方法、將兩個列表合併成一個列表的方法、多個列表合併、將兩個列表的內容合併的方法等多個角度進行了介紹。希望能對大家有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/298006.html