2017-04-30 22 views
-4

我遇到過這個單行代碼,它是一個函數定義,它將列表的列表弄平以生成單個列表。有人能向我解釋,按照術語,這是什麼意思?它是如何工作的?這個代碼是用來壓扁列表的列表是什麼意思?

lambda l : [item for sublist in l for item in sublist] 
+0

[List comprehension explained](http://stackoverflow.com/questions/20639180/python-list-comprehension-explained)。 – xyres

+1

語法錯誤,它一定是'[子列表中的子項列表項]' –

+0

其實它只是一個'SyntaxError' ......但請解釋你不明白的東西。 'lambda'?列表理解?循環?變量? – MSeifert

回答

0

這意味着將2D列表轉換爲1D列表,即扁平列表。

例如,如果你在表單列表:

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

你想要的輸出是:

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

讓我們來看看函數定義:

lambda l : [item for sublist in l for item in sublist] 

,這些等價:

def flatten(l): 
    result = [] 
    for sublist in l: # here shublist is one of the innerlists in each iteration 
     for item in sublist: # One item of a particular inner list 
      result.append(item) #Appending the item to a flat list. 
    return result 
1

遺憾的是,據我所知,沒有辦法真正盲目地在python中解開無限長的嵌套列表。

運算似乎已試圖從

Making a flat list out of list of lists in Python

flatten = lambda l: [item for sublist in l for item in sublist] 

複製我測試上述有關python 3.6,四嵌套結構。可悲的是它只解開外層。我需要三次循環使用它才能完全打開結構。

import numpy as np 
x = np.arange(625).reshape(5,5,5,-1).tolist() #4-nested structure 
flatten = lambda x: [item for sublist in x for item in sublist] 
y = flatten(x) #results in 3-nested structure of length 25. 

同樣的問題也存在於更通用以下功能(需要進口):

from itertools import chain 
y = list(chain.from_iterable(x)) #as per flatten() above, unpacks one level 

多個圖層,如果你不是太在意的開銷,你可以只是做以下內容:

import numpy as np 
y = np.array(x).flatten().tolist() #where x is any list/tuple/numpy array/
          #iterable 

希望以上幫助:)

PS Ahsanul Hafique的解包說明了op所要求的lambda函數的邏輯。我不相信lambda函數,你只需要看看Ahsanul的拆包,看看爲什麼。將主要函數檢查子列表是否是列表或列表元素並在適當情況下解壓縮或追加,從而使用兩個函數創建完全多功能的列表解包器將是微不足道的。