开发者

Python lambda optimization

I've just been learning lambda (About time) and I've figured some things out, I get the general idea.

I have a map() with a lambda here that can surely be made shorter, but I don't know how:

map(lambda x: [ x.split()[0], x.split()[2], x.split()[4] ] , y)

I hoped it would be possible to get the 0, 2 and 4 elements of the split 'x' at once, but currently I have to split it 3 times to get 开发者_JS百科them...


lambda x: operator.itemgetter(0, 2, 4)(x.split())


map(lambda x: x.split()[0:5:2] , y)

Meaning - take x.split() and take the sublist [0:5] with each second item in it.


Just for variety's sake, featuring no itemgetter() call:

    map(lambda x: [x[i] for i in (0,2,4)], (s.split() for s in y))

The (0,2,4) could be replaced with range(0,5,2), of course.
For such a small number of items you could just be explicit with: [x[0], x[2], x[4]]

How it works: The lambda function simply returns a list of the desired elements of the list it is passed. The (s.split() for s in y) is a generator that produces split() versions of the items in list y. Driving all this is the call to map() which applies the lambda function to each one of the split() items from y. In Python 2.x it creates a list of the results from each of these calls.

To answer your follow-up question in the comments about using g = lambda x: [x[i] for i in (0,2,4)] along with (g(s.split()) for s in y) to get rid of map(). That's basically the right idea, but the second expression results in just a generator object. That would need to be wrapped in something like: [g(s.split()) for s in y] to get the result.

If you didn't want to have a separate lambda named g you could use:

    [(lambda x: [x[i] for i in (0,2,4)])(s.split()) for s in y]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜