下面就為大家分享一篇使用Python將數組的元素匯出到變數中(unpacking),具有很好的參考價值,希望對大家有所協助。一起過來看看吧
最近工作中遇到一個問題,需要利用Python將數組(list)或元組(tuple)中的元素匯出到N個變數中,現在將我實現的方法分享給大家,有需要的朋友們可以參考借鑒,下面來一起看看吧。
解決的問題
需要將數組(list)或元組(tuple)中的元素匯出到N個變數中。
解決的方案
任何序列都可以通過簡單的變數賦值方式將其元素分配到對應的變數中,唯一的要求就是變數的數量和結構需要和序列中的結構完全一致。
p = (1, 2)x, y = p# x = 1# y = 2data = ['google', 100.1, (2016, 5, 31)]name, price, date = data# name = 'google'# price = 100.1# date = (2016, 5, 31)name, price, (year, month, day) = data# name = 'google'# price = 100.1# year = 2016# month = 5# day = 31
如果變數結構和元素結構不一致,你將會遇到以下錯誤:
p = (1, 2)x, y, z = pTraceback (most recent call last): File "<pyshell#12>", line 1, in <module> x, y, z = pValueError: not enough values to unpack (expected 3, got 2)
其實這樣的操作不限於元組和數組,在字串中也是可以用的。Unpacking支援大多數我們常見的序列,比如檔案迭代,各種產生器等等。
s = 'Hello'a,b,c,d,e = s# a = 'H'# b = 'e'
如果匯出過程中你想丟掉一些元素,其實Python並不支援這樣的文法,不過你可以指定一些不常用的變數來達到你的目的。
data = ['google', 100.1, (2016, 5, 31)]name, _, (_,month,_) = data# name = 'google'# month = '5'# other fileds will be discarded