如何在python中编辑列表的每个成员

Sha*_*kan 0 python iteration for-loop function

我是python的新手,我正在尝试创建一个大写函数,可以将字符串中的所有单词或仅第一个单词大写.这是我的功能

def capitalize(data, applyToAll=False):
    """depending on applyToAll it either capitalizes
       all the words in the string or the first word of a string"""

    if(type(data).__name__ == "str"):

        wordList = data.split()

        if(applyToAll == True):

            for word in wordList:
                wordList[word] = word.capitalize() #here I am stuck!

            return " ".join(wordList)

        else: return data.capitalize()

    else: return data
Run Code Online (Sandbox Code Playgroud)

基本上,我想编辑项目,但我不知道如何做到这一点.

顺便说一句,这是一个可选的问题:在c#中我有机会调试我的代码,你们在python中使用什么调试?

sen*_*rle 5

实现这一目标的方法是使用列表理解:

>>> l = ['one', 'two', 'three']
>>> [w.capitalize() for w in l]
['One', 'Two', 'Three']
Run Code Online (Sandbox Code Playgroud)

这将创建列表的副本,并将表达式应用于每个项目.

如果你不想创建副本,你可以这样做......

>>> for i, w in enumerate(l):
...     l[i] = w.capitalize()
... 
>>> l
['One', 'Two', 'Three']
Run Code Online (Sandbox Code Playgroud)

...或这个:

l[:] = (w.capitalize() for w in l)
Run Code Online (Sandbox Code Playgroud)

后者可能是就地更改列表的最优雅方式,但请注意它使用的enumerate方法比临时存储更多.

  • 您还可以执行`l [:] =(w.capitalize()for w in l)`来修改列表.列表理解真的是Python的面包和黄油:-) (2认同)