Python中將嵌套列表扁平化的多種實現(xiàn)方法
Python中將嵌套列表扁平化的方法
技術背景
在Python編程中,我們常常會遇到需要將嵌套列表(即列表中包含列表)轉換為一個一維的扁平列表的需求。例如,有一個嵌套列表[[1, 2, 3], [4, 5, 6], [7], [8, 9]],我們希望將其轉換為[1, 2, 3, 4, 5, 6, 7, 8, 9]。以下將介紹多種實現(xiàn)這一目標的方法。
實現(xiàn)步驟
1. 使用嵌套列表推導式
嵌套列表推導式是一種簡潔的實現(xiàn)方式。其基本思路是通過兩層循環(huán),將嵌套列表中的每個元素提取出來,組成一個新的扁平列表。
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ù)可以將多個可迭代對象連接起來,而chain.from_iterable()可以直接接受一個可迭代對象作為參數(shù),將其內部的可迭代對象連接起來。
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ù)可以對可迭代對象求和,當對嵌套列表使用時,結合初始值[],可以實現(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ù)可以對序列中的元素進行累積操作。結合operator.concat或operator.iconcat可以實現(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)
核心代碼
以下是上述各種方法的核心代碼總結:
import itertools
from functools import reduce
import operator
from typing import Iterable
# 嵌套列表推導式
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)))
最佳實踐
- 小規(guī)模數(shù)據(jù):對于小規(guī)模的嵌套列表,嵌套列表推導式是一種簡潔且直觀的選擇,代碼易于理解和維護。
- 大規(guī)模數(shù)據(jù):當處理大規(guī)模的嵌套列表時,
itertools.chain.from_iterable()方法通常具有較高的性能,因為它避免了創(chuàng)建大量的中間列表。 - 任意深度嵌套:如果嵌套列表的深度不確定,使用自定義的遞歸函數(shù)可以處理任意深度的嵌套結構。
常見問題
1. 性能問題
使用sum()函數(shù)和reduce()函數(shù)結合operator.concat時,由于每次操作都會創(chuàng)建一個新的列表對象,會導致性能下降,尤其是處理大規(guī)模數(shù)據(jù)時。建議使用itertools.chain.from_iterable()或自定義遞歸函數(shù)。
2. 字符串處理問題
在處理包含字符串的嵌套列表時,需要注意字符串也是可迭代對象。在自定義遞歸函數(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
complicated = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"]
flat_list = list(flatten(complicated))
print(flat_list)
3. 空列表處理
在使用某些方法時,如reduce()函數(shù),如果輸入的嵌套列表中包含空列表,可能會導致結果不符合預期。在實際使用中,需要根據(jù)具體情況進行處理。
相關文章
從零學python系列之淺談pickle模塊封裝和拆封數(shù)據(jù)對象的方法
這個系列也發(fā)了幾篇文章了,都是個人的一些學習心得的記錄,今天在學習文件數(shù)據(jù)處理的時候了解到有pickle模塊,查找官方文檔學習了一些需要用到的pickle內容。2014-05-05
Python 實現(xiàn)的 Google 批量翻譯功能
這篇文章主要介紹了Python 實現(xiàn)的 Google 批量翻譯功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08

