2017-02-11 48 views
0

我對Python 3很新鮮。當我學習元組時,我在書中找到了這段代碼。Python 3爲什麼在這裏append()可以帶兩個參數?

txt = 'but sort what light in yonder window breaks' 
words = txt.split() 
t = list() 
for word in words: 
    t.append((len(word),word)) 

t.sort(reverse = True) 

res = list() 

for length, word in t: 
    res.append(word) 

print(res) 

我對這段代碼有兩個問題。第一本書說:

第一個循環會建立一個元組列表,其中每個元組都是一個以其長度開頭的單詞。

第一個循環是如何創建元組列表的?從教程中,我學到了像下面這樣創建的元組。

t = ('a',) 
t = 'a', 'b', 'c' 
t = tuple() 

第二個問題是爲什麼append()可以帶兩個參數?

t.append((len(word),word)) 
+2

元組的形式是'(len(word),word)','t'是它們的列表。例如:'(5,「hello」)','append()'在這裏有一個參數,即元組:'(len(word),word)' – Nic

+0

@Nic。非常感謝。我現在明白了 – thereisnowinter

回答

0

append沒有得到兩個參數,它得到一個tuple,當你在教程的元組看到有(var_1, var_2)一樣,所以在這個例子len(word)word兩個記錄變量,所以t是一個元組列表。

+0

非常感謝。我知道了。 – thereisnowinter

相關問題