2016-11-13 77 views
1

編寫一個函數countletter(),該函數應該有一個'for'循環,通過下面的列表步驟 ,並打印城市的名稱和城市名稱中的 字母數。您可以使用len()函數。循環的Python代碼計數字母

citylist = ["Kentucky","New York","LA", "Toronto", 
"Boston","District of Columbia"] 

我在Spyder中使用Python 3.5。我無法從列表中提取字母,然後讓它們在for循環中打印出來。

我有什麼:

def countletter(citylist):  
    city = len(citylist)  
    ct = 0 
    for i in citylist: 
     city = (ne[i]) 

,然後我會被卡住。我擔心這可能是完全錯誤的。我也在如何打印這個問題上苦苦掙扎。

產品應該是:

肯塔基有8個字母。

紐約州有12個字母。

LA有2個字符。

Toronto有7封信件。

Boston有6封信件。

哥倫比亞特區有20個字母。

謝謝你的幫助!

回答

1

您不需要使用索引。只需迭代citylist; for循環將產生每個城市。

def countletter(citylist): 
    for city in citylist: 
     n = len(city) 
     print(city, 'has', n, 'letters.') 


citylist = ["Kentucky","New York","LA", "Toronto", "Boston","District of Columbia"] 
countletter(citylist) 

輸出:

Kentucky has 8 letters. 
New York has 8 letters. 
LA has 2 letters. 
Toronto has 7 letters. 
Boston has 6 letters. 
District of Columbia has 20 letters. 
+0

謝謝你的幫助。我不知道我可以從列表中提取元素並使用len()。謝謝! –

+0

你能幫我解決另一個問題嗎?它在我的個人資料頁面上!我非常感謝幫助! –

0
def countletter(citylist):  
    for index,city in enumerate(citylist): 
     print (index,' : ',city," has ";len(city);" letters". 

應該給:

1:肯塔基州有8個字母。
2:紐約有8個字母。 ...

+0

太謝謝你了! –