我正在學習 python,使用 w3schools python 教程,閱讀了有關 python 如何“將多個值轉換為多個變數”的資訊,并被以下 Casting 程序弄糊涂了。
>>> a=b,c=d = 1,2
>>> print(a,b,c,d)
(1, 2) 1 2 (1, 2)
>>> print(type(a),type(b),type(c),type(d))
<class 'tuple'> <class 'int'> <class 'int'> <class 'tuple'>
>>> x,y,z,t = 1,2,3,4
>>> print(type(x),type(y),type(z),type(t))
<class 'int'> <class 'int'> <class 'int'> <class 'int'>
>>> print(x,y,z,t)
1 2 3 4
>>>
'元組'是什么型別的a,d?
當我研究它時,我認為它們是'int'。
uj5u.com熱心網友回復:
來自語言參考的第 7.2 節,賦值陳述句
賦值陳述句計算運算式串列(請記住,這可以是單個運算式或逗號分隔的串列,后者產生一個元組)并將單個結果物件從左到右分配給每個目標串列。
第一個賦值陳述句
a=b,c=d = 1,2
由運算式串列1, 2(計算結果為元組)和三個目標a、b, c和d組成,它們按以下順序分配:
a = 1, 2
b, c = 1, 2
d = 1, 2
不涉及鑄造。
uj5u.com熱心網友回復:
當你這樣做
a=b,c=d = 1,2
以下發生
d = 1,2 # now d is 2-tuple
b,c=d # 2-tuple is unpacked, now b is 1 and c is 2
a=b,c # new 2-tuple a is created using b and c, now a is 2-tuple (1,2)
uj5u.com熱心網友回復:
我認為添加()到環繞元組時會更清楚。這
a = (b, c) = d = (1, 2)
print(type(a), type(b), type(c), type(d))
print(a, b, c, d)
相當于
a = b, c = d = 1, 2
print(type(a), type(b), type(c), type(d))
print(a, b, c, d)
因此,您將一個元組分配(1, 2)給三個目標a,(b, c)并且d從左到右。(b, c)只是解壓縮值,因此b分配了第一個值并c分配了最后一個值(1, 2)。所有其他變數a,即d只是獲得分配的元組(1, 2)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465604.html
