开发者

Python map vs list comprehension [duplicate]

This question already has answers here: List comprehension vs map (14 answers) Closed 9 years ago.

When comparing these, which do you think is more intuitive / easier to read?

>>> [ord(i) for i in 'some stri开发者_开发问答ng']
[115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103]

>>> map(ord,'some string')
[115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103]

Is there any benefit to the lambda/map way?


I like the first one better and there's an advantage to it. You can instead of

[ord(i) for i in 'some string']

write

(ord(i) for i in 'some string')

and have a generator instead of making a list. Great in some siutations.


I prefer the first one, because I'm more used to it. Somebody doing a lot of functional programming will probably prefer the second one, because it better fits it's mind set. But the second version is to complicated. It can be reduced to

map(ord,'some string')

Which is much more readable and makes the idea more obvious.


I would use: [ord(i) for i in 'some string']. Using map with a lambda is supposedly much slower then using list comprehensions. See Python List Comprehension Vs. Map The first one is also more readable in my opinion.


This seems to have been asked and answered before

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜