python 如何把多個 list 合併?
在 Python 中,有多種方式可以將兩個或多個列表合併成一個列表,具體取決於您對結果的需求。以下是一些常見方法:
方法 1:使用加號運算符 (+
)
將多個列表合併成新列表,原列表保持不變。
list1 = [1, 2, 3] list2 = [4, 5, 6] result = list1 + list2 print(result) # [1, 2, 3, 4, 5, 6]
方法 2:使用 extend()
方法
將一個列表的元素添加到另一個列表中,直接修改原列表。
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1) # [1, 2, 3, 4, 5, 6]
方法 3:使用解包運算符 (*
)
從 Python 3.5 開始,可以使用解包運算符將多個列表合併。
list1 = [1, 2, 3] list2 = [4, 5, 6] result = [*list1, *list2] print(result) # [1, 2, 3, 4, 5, 6]
方法 4:使用 itertools.chain()
適用於合併大量列表時,效率高且適用於懶加載。
from itertools import chain list1 = [1, 2, 3] list2 = [4, 5, 6] result = list(chain(list1, list2)) print(result) # [1, 2, 3, 4, 5, 6]
方法 5:多列表合併
如果有多個列表,可以用以下方法合併它們:
lists = [[1, 2], [3, 4], [5, 6]] result = [item for sublist in lists for item in sublist] print(result) # [1, 2, 3, 4, 5, 6]或者:
from itertools import chain lists = [[1, 2], [3, 4], [5, 6]] result = list(chain(*lists)) print(result) # [1, 2, 3, 4, 5, 6]
推薦使用
- 若只需簡單合併:
+
或extend()
方法簡單直觀。 - 若有多列表且關注性能:
itertools.chain()
是更高效的選擇。
留言板
歡迎留下建議與分享!希望一起交流!感恩!