2017-04-11 85 views
-2

我正在嘗試創建一個接受字符串並將其轉換爲Python中的Pig Latin的應用程序。我到目前爲止的代碼是這樣的:如何編輯Python中的列表中的每個項目?

test = "hello world" 
def PigLatin(): 
    split_test = test.split() 
    for i in split_test: 
     wordlist = list(i) 
     wordlist.append(i[0]) 
     return wordlist 
print PigLatin() 

我試圖把每個單詞的第一個字符,並將其追加到該單詞的結尾。但是,當我運行代碼時,它僅根據返回語句的位置編輯「hello」或「world」。我在這裏做錯了什麼?任何幫助將不勝感激。

回答

0

return語句會導致函數退出並將值返回給調用者。因此,for循環中的return語句將值返回給PigLatin函數調用,並在堆棧外完成。另外,read this please。 代碼:

test = "hello world" 
def PigLatin(): 
    ret = [] 
    split_test = test.split() 
    for i in split_test: 
     wordlist = list(i) 
     wordlist.append(i[0]) 
     ret.append(wordlist) 
    return ret 
print PigLatin() 
+0

謝謝!我不確定返回聲明應該在哪裏,並且我嘗試了這個位置,但它只返回「worldw」這個詞。在嘗試了你的代碼之後,我意識到你創建的空列表也是必需的。 – user7179971

+0

如果答案對您有幫助,請接受。綠色激勵! :) – devautor

相關問題