2016-02-10 55 views
-1

我學習一些Python,和我有以下程序:Python的理解和數據結構

sentence = "the quick brown fox jumps over the lazy dog" 
words = sentence.split() 

print "\n What the hell is this???" 
word_lengths = [(word, len(word)) for word in words if word != "the".lower()] 
print word_lengths 

What the hell is this??? 
[('quick', 5), ('brown', 5), ('fox', 3), ('jumps', 5), ('over', 4), ('lazy', 4), ('dog', 3)] 

我不明白的奇怪的名單,我與後者塊O編碼得到..

它是什麼樣的結構?

在此先感謝!

+7

這是一個元組列表。有什麼問題? –

+4

你可以閱讀關於元組和序列[這裏](https://docs.python.org/3.5/tutorial/datastructures.html#tuples-and-sequences)。 –

+0

謝謝大家,這就是我需要的! – S4rg0n

回答

2

這是一個元組列表。元組僅僅是不可變列表,在形式x, y, z(x, y, z)

當調用此代碼:

word_lengths = [(word, len(word)) for word in words if word != "the".lower()] 

你問Python來製造一個列表[A,B]包含的元組(X,Y)其中x是單詞,y是單詞的長度。

這是語義上幾乎等同於:

word_lengths = [[word, len(word)] for word in words if word != "the".lower()] 

有了,你不能修改一次創建的元組唯一的例外。

注意:要創建1個元素的元組,你需要添加一個逗號,括號內的表達式來區分:(a,)

+0

非常感謝! – S4rg0n