[英]Python Iterating over lists in lists with map()
So my intention is to iterate over lists in lists with map, filter and lambda eg: 所以我的目的是迭代列表中的列表,包括map,filter和lambda,例如:
[ [33,3,3,0] , [34,1,0,4] ] should result in [ [33,3,3] , [34,1,4] ] [[33,3,3,0],[34,1,0,4]]应该产生[[33,3,3],[34,1,4]]
def no_zeros(lst):
a=map(filter(lambda x:(y==0 for y in x) ,lst),lst)
print (list(a))
#(says that filter is not callable)
I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . 我知道这段代码不起作用,但我不知道我到底做错了什么,因为我仍然是lambda等新手。我已经尝试了不同的东西,比如在lambda之后移动过滤器,但是没有似乎也工作。 Im gratefull for any kind of tipps or help. 我感激任何一种tipps或帮助。
map
applies the function in first parameter to the second parameter. map
将第一个参数中的函数应用于第二个参数。 It tries to call your filter
object... 它试图调用你的filter
对象......
A fixed version would be: 固定版本将是:
list(map(lambda z: list(filter(None,z)),lst))
(still not very clear even if it yields the expected result... it took me 3 or 4 tries to get it right by trial & error, and the fact that filter
& map
need to be iterated upon in Python 3 doesn't help and kills the whole hype about those fashionable keywords) (即使它产生了预期的结果,仍然不是很清楚......我通过试验和错误尝试了3到4次尝试,并且需要在Python 3中迭代filter
和map
这一事实无济于事关于那些时髦的关键词杀死了整个炒作)
At this point of lambda/map/filter
complexity you'd be better off with a list comprehension: 在lambda/map/filter
复杂度的这一点上,你最好使用列表理解:
lst = [ [33,3,3,0] , [34,1,0,4] ]
result = [ [x for x in sl if x] for sl in lst]
print(result)
result: 结果:
[[33, 3, 3], [34, 1, 4]]
The thing is that map
expects a function/callable as a first argument but you're giving it the result of a filter
. 问题是map
希望函数/可调用作为第一个参数,但是你给它一个filter
的结果。
You can fix this by applying filter
to the sublists iterated by map
: 您可以通过将filter
应用于由map
迭代的子列表来解决此问题:
def no_zeros(lst):
a = map(lambda x: filter(lambda y: y != 0, x), lst)
print(list(a))
By the way, you can do the same thing with list comprehensions: 顺便说一句,你可以用列表推导做同样的事情:
def no_zeros(lst):
a = [[y for y in x if y != 0] for x in lst]
print(a)
lst = list(map(lambda k: list(filter(lambda l: l != 0, k)), lst))
This should do the trick. 这应该可以解决问题。 You need apply a lambda on each element in the list through a filter. 您需要通过过滤器在列表中的每个元素上应用lambda。 Be aware nested lambdas are ugly. 请注意嵌套的lambdas是丑陋的。
Here is one possibility: 这是一种可能性:
import itertools
a = [ [33,3,3,0] , [34,1,0,4] ]
list(map(list, map(filter, itertools.repeat(bool), a)))
# [[33, 3, 3], [34, 1, 4]]
Another solution might be: 另一种解决方案可能是
def no_zeros(lst):
if isinstance(lst, list):
for i in lst:
while 0 in i:
i.remove(0)
print(lst)
else:
raise TypeError("lst must be type of list")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.