在列表元素的末尾添加一个单词

时间:2015-08-13 03:16:51

标签: python list

我有清单:

mylist = ["all dogs go", "why does one", "fell down so hard I"]

是否有一项功能允许我将"moo"添加到mylist中所有元素的末尾?

3 个答案:

答案 0 :(得分:7)

使用列表推导:

>>> mylist[:] = [word.strip() + " moo" for word in mylist]
>>> print mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

答案 1 :(得分:4)

您可以使用列表推导来执行此操作:

>>> mylist = ["all dogs go", "why does one", "fell down so hard I"]
>>> mylist = [x + " moo" for x in mylist]
>>> mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

这会创建一个新的列表,所以你也可以使用for循环来做同样的事情(这会改变现有的列表对象,虽然这在像这样的小例子中并不重要):

>>> mylist
['all dogs go', 'why does one', 'fell down so hard I']
>>> for idx in xrange(len(mylist)):
...     mylist[idx] = mylist[idx] + " moo"
... 
>>> mylist
['all dogs go moo', 'why does one moo', 'fell down so hard I moo']

对于您编辑过的问题,如果您的模式对所有元素都有效,则可以使用以下内容:

>>> mylist = ["8 - 9 -", "7 - 6 -", "5 - 4 -"]
>>> mylist = [x[:-1] for x in mylist]
>>> mylist
['8 - 9 ', '7 - 6 ', '5 - 4 ']

答案 2 :(得分:1)

只需使用append

mylist.append('moo')
>>> mylist
['all dogs go', 'why does one', 'fell down so hard I', 'moo']

编辑:

如果你想追加“moo'对于列表中的每个元素,请使用@mu的建议(没有双关语)。对不起@ozgur,我没有故意让你离开,双关语意在......