原文第2章第3節(jié)
分解序列(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
如果執(zhí)行下列代碼:
>>> for x, y in pairs:
if x == y:
same_count = same_count + 1
就可以得到:
>>> same_count
2
更多可見(jiàn)Python 3技巧:分解序列 - 極客范
列表推導(dǎo)式(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.
一行代碼直接完成對(duì)列表的便利操作并返回值。
例如,
>>> 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>]
更多見(jiàn)這里。
列表推導(dǎo)式的效果也可以用高階函數(shù)的方式來(lái)達(dá)到,但前者更為常見(jiàn)(個(gè)人覺(jué)得前者更利于理解)。
數(shù)據(jù)類(lèi)型的閉合性
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.
例如,列表自身可以組成列表的元素。