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

时间:2019-05-12 15:37:21

标签: python list

我有以下列表对象列表

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]

我想从此列表中删除所有零。

我遵循了这个question并按照如下代码进行编码。

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

但是我正在获取过滤器对象列表作为输出。代码中有什么错误。

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

4 个答案:

答案 0 :(得分:7)

您忘记使用filter强制转换内部list函数,执行此操作时,代码将按预期运行:)

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)

输出将为

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

更简单的理解方式是使用列表理解

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)

输出将为

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

答案 1 :(得分:0)

尝试一下:

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

输出

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:-1)

您只需要包装过滤器,而不是整个语句:

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

此外,您可以跳过索引,并按myList中的列表进行迭代:

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