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

时间:2011-07-28 22:50:41

标签: python function for-loop iteration

我是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

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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

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

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

......或者这个:

l[:] = (w.capitalize() for w in l)

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

答案 1 :(得分:3)

使用列表理解:

def capitalize(s, applyToAll=False):
    if applyToAll:
        l = [w.capitalize() for w in s.split()]
        return " ".join(l)
    else:
        return s.capitalize()
  

你们在python中用什么来调试?

复杂的代码片段的

print语句,其他任何东西的交互式解释器。我通过编写了很多测试,并使用nose运行它们。