簡體   English   中英

在python中的子列表上使用地圖和過濾器功能

[英]Using map and filter function on a sublist in python

L = [[5, 0, 6], [7, 22], [0, 4, 2], [9, 0, 45, 17]]

我確實有此列表,我的任務是刪除0 必須同時使用map()filter()函數。

提示該任務可以通過使用map,filter和lambda表達式的單個表達式解決。

我已經嘗試了好一陣子了,但我還是不明白。 您不必完全解決它,但將不勝感激。

我假設我使用map()遍歷外部列表,但是如何使用子列表調用filter()

L2 = map(lambda x: filter(lambda x: x<>0 ,L),L)

使用mapfilter您可以編寫以下內容

>>> list(map(lambda i: list(filter(lambda i: i != 0, i)), L))
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

對於它的價值,我更喜歡嵌套列表理解

>>> [[i for i in j if i != 0] for j in L]
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

您可以使用以下事實:如果filter()的第一個參數為None則僅保留那些為“ true”的項。 0被認為是錯誤的,因此0將被刪除。

解決方案可以這樣寫:

>>> L = [[5, 0, 6], [7, 22], [0, 4, 2], [9, 0, 45, 17]]
>>> map(lambda l: filter(None, l), L)
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

如果您使用的是Python 3,則可以在filter()map()的結果上調用list() map()以獲得所需的列表:

>>> map(lambda l: filter(None, l), L)
<map object at 0x7fb34856be80>
>>> list(map(lambda l: list(filter(None, l)), L))
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

現在,這變得越來越難以理解。 列表理解可能更好。

>>> [[item for item in l if item] for l in L]
[[5, 6], [7, 22], [4, 2], [9, 45, 17]]

對我來說,關鍵是要考慮類型,這是Python中有點陌生的概念。

map接受一個函數和一個可迭代的對象,並返回一個可迭代對象,該對象是將該函數應用於可迭代參數的每個元素的結果。

map(f: "some function",
    lst: "some iterable") -> "(f(e) for e in lst)"

在這種情況下,外部列表的元素本身就是列表! 並且您打算將filter函數應用於每個函數以消除零。 filter需要一個函數(它本身需要一個元素,如果該元素應該在結果中,則返回True如果應該將其刪除,則返回False )以及這些元素的列表。

filter(f: "some_func(e: 'type A') -> Bool",
       lst: "some_iterable containing elements of type A") ->
       "(e for e in lst if f(e))":

然后,您的filter函數就是filter(lambda x: x != 0, some_list)lambda sublst: filter(lambda x: x!=0, sublst) 將其應用到map ,您將獲得:

map(lambda sublst: filter(lambda x: x!=0, sublst), lst)

要么

[[x for x in xs if x!=0] xs in xss]

這在Haskell中更容易表達,Haskell更自然地處理mapfilter

map (filter (/=0)) lst
-- or still with a list comprehension
[[x | x <- xs, x!=0] | xs <- xss]

您可以在過濾器函數中使用None參數,並執行類似的操作

[list(filter(None, i)) for i in a]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM