Python 如何在列表的每个元素末尾添加一个单词?

Python 如何在列表的每个元素末尾添加一个单词?,python,list,Python,List,我有以下清单: mylist = ["all dogs go", "why does one", "fell down so hard I"] 是否有一个函数允许我在mylist中的每个元素末尾添加moo一词?您可以使用列表理解来完成此操作: >>> mylist = ["all dogs go", "why does one", "fell down so hard I"] >>> mylist = [x + " moo" for x in mylist]

我有以下清单:

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

是否有一个函数允许我在mylist中的每个元素末尾添加moo一词?

您可以使用列表理解来完成此操作:

>>> 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 ']

您可以使用列表理解来执行此操作:

>>> 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 ']

使用列表理解:

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

使用列表理解:

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

编辑:

如果您想将“moo”附加到列表中的每个元素,请使用@mu no pun的建议。抱歉@ozgur,我不是故意把你排除在外,双关语是有意的…

只需使用append:

编辑:


如果您想将“moo”附加到列表中的每个元素,请使用@mu no pun的建议。抱歉@ozgur,我不是故意把你排除在外,双关语是有意的…

你能提供想要的输出来澄清吗?你能提供想要的输出来澄清吗?mu無, ozgur的方法正是我想要的,但谢谢你的回答無, ozgur的方法正是我想要的,但谢谢你的回答。这里是双关语的+1: