PythonTip >> 博文 >> python

Comprehension in Python

zihua 2014-01-20 23:01:02 点击: 956 | 收藏


Python is a wonderful dynamic language offering various functional programming features, including standard library modules itertools and functools borrowed from Haskell and Standard ML. Some see it as the best of both worlds as not only can you perform complex tasks with these functional programming tools but you can do it using simple readable code thanks to Python’s beautiful syntax.

Early on in my experience with Python I discovered list comprehension. Traditionally, to generate a list (an array) of values according to a particular rule, let’s say a list of square numbers, we initialise an empty list, and loop over the domain, square each one and add it to the list:

However, using list comprehension allows you to generate this list in a single (readable) line:

I really like this shorthand. It’s a list definition in the assignment. Not assigning [] to the variable, then building it up, just assigning it to exactly what you want it to be. Concise!

You can do list comprehension with two domains, say a rows range and a columns range:

This example generated a single list of all the tuples of coordinates of a grid – the second ignoring the diagonal – which is equivalent to:

The following example generates a nested list of tuples, separating each row:

You can wrap a list comprehension in a function such as sum:

An example of string generation from joining comprehended lists:

There are other ways you can manipulate list comprehension but this gives you the idea.

More recently I discovered it’s also possible to comprehend dictionaries and sets in the same way, using curly braces instead of square brackets:

Note the sets only contain each value once, as it cannot contain duplicates.

Finally, another interesting feature is generator comprehension, known as generator expressions:

Generators don’t keep the list in memory. Instead, each time the next() method is called on it, it returns the next value. This can be done in custom functions by use of the keyword ‘yield’ rather than ‘return’. Return would be used to send a whole list back, whereas yield could be used to return each value individually, when prompted. You can also request a list from a generator by wrapping it in the list function.

Read more on list comprehension and data structures at docs.python.org

原文链接:http://www.wumii.com/item/QQuxV83H

作者:zihua | 分类: python | 标签: python | 阅读: 956 | 发布于: 2014-01-20 23时 |