如何在列表的每个元素的末尾添加单词? [英] How to add a word at the end of each element of a list?

查看:80
本文介绍了如何在列表的每个元素的末尾添加单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有清单:

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

有没有能让我在mylist中每个元素的末尾添加单词"moo"的功能?

Is there a function that will allow me to add the word "moo" to the end of each element in mylist?

推荐答案

您可以使用列表解析来做到这一点:

You can use a list comprehension to do that:

>>> 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循环执行相同操作(这将更改现有列表对象,尽管在像这样的小示例中这并不重要)

That creates a new list, so you can also use a for loop to do the same (which changes existing list object, though that shouldn't really matter in small examples like this one):

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


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


As for your edited question, you could use the below if your pattern is valid for all elements:

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

这篇关于如何在列表的每个元素的末尾添加单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆