2014-02-26 104 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() 
相关问题