1

我经常看到类似这样的代码:

return [(var, val) for val in self.domains[var]
                    if self.nconflicts(var, val, assignment) == 0]

我就像该死的那样性感。但是有时我会尝试删除它,但会出现语法错误。这种很好的代码编写形式有什么特殊的规则可以颠倒forandif语句的典型位置吗?

4

4 回答 4

6

They're called list comprehensions. The basic syntax is (I'm using parens to group my words, not as part of the syntax):

[(an expression involving x) for x in someList if (some condition)]

If the condition evaluates to true, the resulting list includes the (expression involving x). So, for example, the following list comprehension uses this to only include strings in the resulting list.

>>> myList = [1,"hello",5.4,"world"]
>>> [elem for elem in myList if type(elem)==str]
['hello', 'world']

Note that the if part is optional, and the expression involving x can be as simple as just x (often used when you are just filtering out elements from another list).

In fact, the expression involving x doesn't really have to have x in it at all. For example, if for some reason you wanted a list of 0's as long as your name you could do this:

>>> [0 for letter in "Matthew"]
[0, 0, 0, 0, 0, 0, 0]

For when you don't need the list to stick around after you make it, use generator expressions instead. (Generator expressions and list comprehensions have the same syntax.)

于 2012-10-19T03:33:53.730 回答
2

See list comprehensions in the Python tutorial documentation. There are quite a number of things you can do with this syntax, including creating lists, sets, and dictionaries.

于 2012-10-19T03:33:45.670 回答
2

The concept is called list comprehension,

http://www.secnetix.de/olli/Python/list_comprehensions.hawk

Take a look at lambda functions too,

http://www.secnetix.de/olli/Python/lambda_functions.hawk

于 2012-10-19T03:35:01.440 回答
2

尽管您的示例代码确实是一个列表推导式,但您偶尔也会看到内联条件的反向 if 语法:

a if b else c
于 2012-10-19T03:39:24.900 回答