CP学习笔记(4) - 序列

原文第2章第3节

分解序列(sequence unpacking)
The pattern of binding multiple names to multiple values in a fixed-length sequence。
序列中各值赋予不同变量名。

>>> pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]

>>> same_count = 0

如果执行下列代码:

>>> for x, y in pairs:
        if x == y:
            same_count = same_count + 1

就可以得到:

>>> same_count
2

更多可见Python 3技巧:分解序列 - 极客范

列表推导式(list comprehension)
An expression that can performs such a sequence processing operation which can be expressed by evaluating a fixed expression for each element in a sequence and collecting the resulting values in a result sequence.
一行代码直接完成对列表的便利操作并返回值。
例如,

>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]

# Another Example
>>> [x for x in odds if 25 % x == 0]
[1, 5]

通式:

[<map expression> for <name> in <sequence expression> if <filter expression>]

更多见这里

列表推导式的效果也可以用高阶函数的方式来达到,但前者更为常见(个人觉得前者更利于理解)。

数据类型的闭合型
In general, a method for combining data values has a closure property if the result of combination can itself be combined using the same method.
例如,列表自身可以组成列表的元素。

其它

posted on 2015-12-08 21:18  Rim99  阅读(231)  评论(0编辑  收藏  举报

导航