Python中將嵌套列表扁平化的多種實(shí)現(xiàn)方法
Python中將嵌套列表扁平化的方法
技術(shù)背景
在Python編程中,我們常常會(huì)遇到需要將嵌套列表(即列表中包含列表)轉(zhuǎn)換為一個(gè)一維的扁平列表的需求。例如,有一個(gè)嵌套列表[[1, 2, 3], [4, 5, 6], [7], [8, 9]]
,我們希望將其轉(zhuǎn)換為[1, 2, 3, 4, 5, 6, 7, 8, 9]
。以下將介紹多種實(shí)現(xiàn)這一目標(biāo)的方法。
實(shí)現(xiàn)步驟
1. 使用嵌套列表推導(dǎo)式
嵌套列表推導(dǎo)式是一種簡(jiǎn)潔的實(shí)現(xiàn)方式。其基本思路是通過兩層循環(huán),將嵌套列表中的每個(gè)元素提取出來,組成一個(gè)新的扁平列表。
xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] flat_list = [x for xs in xss for x in xs] print(flat_list)
2. 使用itertools.chain()或itertools.chain.from_iterable()
itertools
模塊提供了高效的迭代工具。chain()
函數(shù)可以將多個(gè)可迭代對(duì)象連接起來,而chain.from_iterable()
可以直接接受一個(gè)可迭代對(duì)象作為參數(shù),將其內(nèi)部的可迭代對(duì)象連接起來。
import itertools list2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] # 使用 chain() merged1 = list(itertools.chain(*list2d)) # 使用 chain.from_iterable() merged2 = list(itertools.chain.from_iterable(list2d)) print(merged1) print(merged2)
3. 使用sum()函數(shù)
sum()
函數(shù)可以對(duì)可迭代對(duì)象求和,當(dāng)對(duì)嵌套列表使用時(shí),結(jié)合初始值[]
,可以實(shí)現(xiàn)列表的扁平化。但這種方法效率較低,不適合處理大規(guī)模數(shù)據(jù)。
xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] flat_list = sum(xss, []) print(flat_list)
4. 使用functools.reduce()
reduce()
函數(shù)可以對(duì)序列中的元素進(jìn)行累積操作。結(jié)合operator.concat
或operator.iconcat
可以實(shí)現(xiàn)列表的扁平化。
from functools import reduce import operator xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] # 使用 operator.concat out1 = reduce(operator.concat, xss) # 使用 operator.iconcat out2 = reduce(operator.iconcat, xss, []) print(out1) print(out2)
5. 自定義遞歸函數(shù)
通過遞歸的方式,可以處理任意深度的嵌套列表。
from typing import Iterable def flatten(items): for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x simple = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] flat_list = list(flatten(simple)) print(flat_list)
核心代碼
以下是上述各種方法的核心代碼總結(jié):
import itertools from functools import reduce import operator from typing import Iterable # 嵌套列表推導(dǎo)式 def nested_list_comprehension(xss): return [x for xs in xss for x in xs] # itertools.chain.from_iterable() def itertools_chain(xss): return list(itertools.chain.from_iterable(xss)) # sum() def pythons_sum(xss): return sum(xss, []) # functools.reduce() with operator.concat def reduce_concat(xss): return reduce(operator.concat, xss) # functools.reduce() with operator.iconcat def reduce_iconcat(xss): return reduce(operator.iconcat, xss, []) # 自定義遞歸函數(shù) def custom_flatten(items): for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from custom_flatten(x) else: yield x xss = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] print(nested_list_comprehension(xss)) print(itertools_chain(xss)) print(pythons_sum(xss)) print(reduce_concat(xss)) print(reduce_iconcat(xss)) print(list(custom_flatten(xss)))
最佳實(shí)踐
- 小規(guī)模數(shù)據(jù):對(duì)于小規(guī)模的嵌套列表,嵌套列表推導(dǎo)式是一種簡(jiǎn)潔且直觀的選擇,代碼易于理解和維護(hù)。
- 大規(guī)模數(shù)據(jù):當(dāng)處理大規(guī)模的嵌套列表時(shí),
itertools.chain.from_iterable()
方法通常具有較高的性能,因?yàn)樗苊饬藙?chuàng)建大量的中間列表。 - 任意深度嵌套:如果嵌套列表的深度不確定,使用自定義的遞歸函數(shù)可以處理任意深度的嵌套結(jié)構(gòu)。
常見問題
1. 性能問題
使用sum()
函數(shù)和reduce()
函數(shù)結(jié)合operator.concat
時(shí),由于每次操作都會(huì)創(chuàng)建一個(gè)新的列表對(duì)象,會(huì)導(dǎo)致性能下降,尤其是處理大規(guī)模數(shù)據(jù)時(shí)。建議使用itertools.chain.from_iterable()
或自定義遞歸函數(shù)。
2. 字符串處理問題
在處理包含字符串的嵌套列表時(shí),需要注意字符串也是可迭代對(duì)象。在自定義遞歸函數(shù)中,通常需要排除字符串類型,以避免將字符串拆分為單個(gè)字符。例如:
from typing import Iterable def flatten(items): for x in items: if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): yield from flatten(x) else: yield x complicated = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"] flat_list = list(flatten(complicated)) print(flat_list)
3. 空列表處理
在使用某些方法時(shí),如reduce()
函數(shù),如果輸入的嵌套列表中包含空列表,可能會(huì)導(dǎo)致結(jié)果不符合預(yù)期。在實(shí)際使用中,需要根據(jù)具體情況進(jìn)行處理。
相關(guān)文章
基于Python+Tkinter實(shí)現(xiàn)一個(gè)簡(jiǎn)易計(jì)算器
Tkinter作為Python的標(biāo)準(zhǔn)庫,是非常流行的Python GUI工具,同時(shí)也是非常容易學(xué)習(xí)的。本文將利用Tkinter繪制一個(gè)簡(jiǎn)單的計(jì)算器,感興趣的可以試一試2022-01-01Python 通過打碼平臺(tái)實(shí)現(xiàn)驗(yàn)證碼的實(shí)現(xiàn)
這篇文章主要介紹了Python 通過打碼平臺(tái)實(shí)現(xiàn)驗(yàn)證碼的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05解決Cannot?set?up?a?python?SDK?at?Python問題
本文主要介紹了解決Cannot?set?up?a?python?SDK?at?Python問題,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-04-04Python中的copy()函數(shù)詳解(list,array)
這篇文章主要介紹了Python中的copy()函數(shù)詳解(list,array),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09如何使用?profile?進(jìn)行python代碼性能分析
對(duì)代碼優(yōu)化的前提是需要了解性能瓶頸在什么地方,程序運(yùn)行的主要時(shí)間是消耗在哪里,對(duì)于比較復(fù)雜的代碼可以借助一些工具來定位,python?內(nèi)置了豐富的性能分析工具,本文介紹如何使用profile進(jìn)行python代碼性能分析,感興趣的朋友一起看看吧2024-12-12