开发者

Nested lambda expressions in python map and reduce

My code currently contains, as part of the condition for a while loop:

reduce(operator.or_, map(lambda y: reduce(operator.or_, map(lambda x: x[0] == y, data[testedoffset:])), footers))

It's purpose is to check if a given slice of a python array.array instance contains one of several specific byte values.

The error I'm getting is:

开发者_如何学GoNameError: global name 'y' is not defined

So I'm pretty sure it's a scoping issue. But I can't think of a way to do what I want from here.


I see you found the answer on your own, but while you're here... That code really could use some work.

I'm not entirely sure why you're mapping that expression based on data[testedoffset:] across the footers sequence. That doesn't seem to have any effect whatsoever, unless your __getitem__ has side effects.

But the whole map + reduce + operator.or_ thing gives me the willies.

Try something more like this:

y = 'whatever'
if any(x[0] == y for x in data[offset:]):
    print "yep, it's in there"


That sure is not a scoping issue and it is clearly an unpythonic expression. Here is my attempt to understand it and I find that you have to passing y to the lambda expression.

reduce(operator.or_,
       map(lambda y: reduce(operator.or_, map(lambda x: x[0] == y, data[testedoffset:]))
                ,#Where is y
           , footers))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜