Reputation: 4766
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>,
Upvotes: 1
Views: 148
Reputation: 42143
You could also do this with a list comprehension:
cleaned = [ [e for e in row if e != 0] for row in myList ]
Upvotes: 0
Reputation: 1039
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 = [list(filter(lambda j:j!=0, inner_list) for inner_list in myList]
Upvotes: -1
Reputation: 20490
You forgot to cast the inner filter
function with a list
, when you do that, the code works as expected :)
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]]
Upvotes: 7
Reputation: 6920
Try this :
newList = [list(filter(lambda j:j!=0, i)) for i in myList]
OUTPUT :
[[123, 345], [45], [67, 8, 5, 6, 7]]
Upvotes: 0