我有清单:
mylist = ["all dogs go", "why does one", "fell down so hard I"]
是否有功能允许我将单词添加"moo"
到中的每个元素的末尾mylist
?
您可以使用列表推导来做到这一点:
>>> 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 ']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句