流暢的python和cookbook學習筆記(二),pythoncookbook

來源:互聯網
上載者:User

流暢的python和cookbook學習筆記(二),pythoncookbook
1.元組拆包和解壓序列賦值

  任何的序列 (或者是可迭代對象) 可以通過一個簡單的指派陳述式解壓並賦值給多個 變數。唯一的前提就是變數的數量必須跟序列元素的數量是一樣的。

  1.平行賦值:

>>> x = (1, 2) >>> a, b = x  # 元組拆包 >>> a1>>> b2

  2.以用 * 運算子把一個可迭代對象拆開作為函數的參數:

>>> divmod(20, 8)  # 20求8的餘,2 * 8 + 4 == 20(2, 4) >>> t = (20, 8)>>> divmod(*t) (2, 4) >>> quotient, remainder = divmod(*t) >>> quotient, remainder   # 商和餘數(2, 4)

  3.函數中用 *args 來擷取不確定數量的參數:

>>> a, b, *rest = range(5)>>> a, b, rest (0, 1, [2, 3, 4]) >>> a, b, *rest = range(3)>>> a, b, rest(0, 1, [2]) >>> a, b, *rest = range(2) >>> a, b, rest(0, 1, [])

  4.在平行賦值中,* 首碼只能用在一個變數名前面,但是這個變數可以出現在賦值運算式的任意位置:

>>> a, *body, c, d = range(5) >>> a, body, c, d (0, [1, 2], 3, 4) >>> *head, b, c, d = range(5) >>> head, b, c, d ([0, 1], 2, 3, 4)

.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.