序列

原文第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.
例如,列表自身可以組成列表的元素。

其它

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容