简体   繁体   English

从列表列表中删除所有匹配的值

[英]Remove all matching value from a list of lists

I have following list of lists object 我有以下列表对象列表

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]

And I want to remove all zeroes from this list. 我想从此列表中删除所有零。

I followed this question and coded like following. 我遵循了这个问题,并按如下所示进行编码。

myList = list(filter(lambda j:j!=0,myList[i]) for i in range(len(myList)))

But I am getting the list of filter object as the output. 但是我正在获取过滤器对象列表作为输出。 What is the error in the code. 代码中有什么错误。

[<filter object at 0x7fe7bdfff8d0>, <filter object at 0x7fe7a6eaaf98>, <filter object at 0x7fe7a6f08048>,

You forgot to cast the inner filter function with a list , when you do that, the code works as expected :) 您忘记使用list强制转换内部filter功能,执行此操作时,代码将按预期工作:)

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]]

#Cast inner filter into a list
myList = list(list(filter(lambda j:j!=0,myList[i])) for i in range(len(myList)))
print(myList)

The output will be 输出将是

[[123, 345], [45], [67, 8, 5, 6, 7]]

Also a simpler way of understanding will be to use a list-comprehension 同样,更简单的理解方式是使用列表理解

myList = [[123,0.0,345,0.0,0.0,0.0],
 [45,0.0,0.0,0.0],
 [67,8,0.0,5,6,7,0.0]]

#Using list comprehension, in the inner loop check if item is non-zero
myList = [ [item for item in li if item != 0] for li in myList ]
print(myList)

The output will be 输出将是

[[123, 345], [45], [67, 8, 5, 6, 7]]

Try this : 尝试这个 :

newList = [list(filter(lambda j:j!=0, i)) for i in myList]

OUTPUT : 输出

[[123, 345], [45], [67, 8, 5, 6, 7]]

您还可以通过列表理解来做到这一点:

cleaned = [ [e for e in row if e != 0] for row in myList ]

You just need to wrap filter, not the whole statement: 您只需要包装过滤器,而不是整个语句:

myList = [list(filter(lambda j:j!=0,myList[i]) for i in range(len(myList))]

Also, you can skip the index, and iterate by lists in myList : 另外,您可以跳过索引,并通过myList的列表进行myList

myList = [list(filter(lambda j:j!=0, inner_list) for inner_list in myList]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM