2014-02-26 105 views
0

我有一個列表,我的教授希望我們使用循環打印它。我該怎麼做?python 2.7.6使用循環打印包含五個字符串的列表

plants = 'apples, beans, carrots , dates , eggplant' 
for i in list(plants): 
    print plants 

這裏是我正在使用的代碼。我需要解決什麼問題?當我這樣做時,我得到了五十行的清單。

編輯:

忘了添加最後一步。它需要在列表之前打印出來: '列表中的項目是:'我該怎麼做?我這樣做:

print 'The items in the list are: ' + plant 

這是基於Martijn彼得斯的答案。 遺憾的混亂

預期的結果是這樣的:

在列表中的項目有:

蘋果豆類胡蘿蔔日期茄子

+2

這不是一個列表,這是一個單一的字符串。 –

+0

嗯,對於你想要在循環體中「打印i」的一件事,但是你正在循環字符串中的字符。 – geoffspear

+0

如果你有一個字符串,你可能想[split](http://docs.python.org/2.7/library/stdtypes.html#str.split)它。 – Matthias

回答

2

您首先需要根據您的具體情況製作list。現在,plantsstring,當您遍歷它時,您一次只會得到一個字符。您可以使用split將此字符串轉換爲列表。

>>> plants = 'apples, beans, carrots , dates , eggplant'.split(', ') 
>>> plants 
['apples', ' beans', ' carrots ', 'dates ', 'eggplant'] 
>>> for plant in plants: 
    print plant 
apples 
beans 
carrots 
dates 
eggplant 
2

你有一個字符串,包含用逗號文本在他們中。這將是一個字符串列表:

plants = ['apples', 'beans', 'carrots', 'dates', 'eggplant'] 

和你的循環將如下所示:

for plant in plants: 
    print plant 

你的代碼,而不是環繞在輸入字符串的單個字符:

>>> list('apples, beans, carrots , dates , eggplant') 
['a', 'p', 'p', 'l', 'e', 's', ',', ' ', ' ', 'b', 'e', 'a', 'n', 's', ',', ' ', ' ', 'c', 'a', 'r', 'r', 'o', 't', 's', ' ', ',', ' ', 'd', 'a', 't', 'e', 's', ' ', ',', ' ', 'e', 'g', 'g', 'p', 'l', 'a', 'n', 't'] 

你也可以在這些逗號分割,並從結果中刪除多餘的空格:

plants = 'apples, beans, carrots , dates , eggplant' 
for plant in plants.split(','): 
    print plant.strip() 
相關問題