資料結構和演算法——將序列分解為單獨的變數

來源:互聯網
上載者:User

標籤:圖片   for   spl   資料   進階   print   元組   實現   splay   

 

①問題:假如有一個包含N多個元素的元組或者序列,現在想分解為N個單獨的變數。

1 L = (4, 5)2 x, y = L
View Code

②進階篇:

data = [‘sb‘, ‘大鐵鎚‘, ‘51‘, (2018, 6, 2)]a, b, c, date = dataa=‘sb‘b=‘大鐵鎚‘c=51date=(2018, 6, 2)

③

data = [‘sb‘, ‘大鐵鎚‘, ‘51‘, (2018, 6, 2)]a, b, c, (year, mon, day) = datayear = 2018mon = 6day = 2
View Code

那麼接下來問題來了,這個是知道列表具體多少的情況下去實現的,假如說未知呢?那就會用到*運算式去分解可迭代對象了

*式文法在迭代一個邊長的元組序列時候相當有用的,撅個例子:

records = [    (‘foo‘, 1, 2),    (‘bar‘, ‘hi‘),    (‘foo‘, 3, 4),]def do_foo(x, y):    print(‘foo‘, x, y)def do_bar(s):    print(‘bar‘, s)for tag, *args in records:    if tag == ‘foo‘:        do_foo(*args)    elif tag == ‘bar‘:        do_bar(*args)
View Code

 

資料結構和演算法——將序列分解為單獨的變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.