2016-04-25 22 views

回答

1

使用split()方法句子得到的單詞列表中sentence

words = sentence.split() 

然後使用enumerate內置功能來構建一個生成器,提升相關聯將數字與列表中的單詞相關聯。默認情況下enumerate從0開始的編號,但你希望它是從1開始,所以通過該值作爲第二個參數:

numbered_words = enumerate(words, 1) 

然後使用dict內置功能來構建一個字典從該輸出發電機。幸運的是,生成器以與您嘗試構建的格式相匹配的格式發出它的(數字,單詞)元組 - dict通過使用元組中的第一項作爲鍵構建字典,第二個作爲值:

sentence_dict = dict(numbered_words) 

您可以堵塞所有成一條線,如果你想成爲簡潔:

sentence_dict = dict(enumerate(sentence.split(), 1)) 

enumerate發生器是唯一棘手的部分。 enumeratexrange的相似之處在於它不返回序列,它返回可從中提取序列的對象。爲了證明發生些什麼事,你可以用一個for循環提取(數字,字)從enumerate發生器對並打印出來:

for num, word in enumerate(['a', 'b', 'c', 'd'], 57): 
    print 'num is', num, 'and word is', word 

這說明這一點:

num is 57 and word is a 
num is 58 and word is b 
num is 59 and word is c 
num is 60 and word is d 
+0

感謝您的幫助 –

相關問題