开发者

What are the advantage and disadvantages of using a list comprehension in Python 2.54-6?

I've heard that list comprehensions can be slow sometimes, but I'm not sure why? I'm new to Python (coming from a C# backgrou开发者_Python百科nd), and I'd like to know more about when to use a list comprehension versus a for loop. Any ideas, suggestions, advice, or examples? Thanks for all the help.


Use a list comprehension (LC) when it's appropriate.

For example, if you are passing any ol' iterable to a function, a generator expression (genexpr) is often more appropriate, and a LC is wasteful:

"".join([str(n) for n in xrange(10)])
# becomes
"".join(str(n) for n in xrange(10))

Or, if you don't need a full list, a for-loop with a break statement would be your choice. The itertools module also has tools, such as takewhile.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜