如何在Python中编辑列表的每个成员 [英] how to edit each member of a list in python

查看:146
本文介绍了如何在Python中编辑列表的每个成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我试图创建一个大写的函数,用大写字母或者只是第一个单词。这里是我的函数

$ $ p $ $ $ c $ def $大写字母数据applyToAll = False
取决于applyToAll它或者大写
字符串中的所有单词或字符串的第一个单词

if(type(data).__ name__ ==str):

wordList = data.split()

if(applyToAll == True):

wordList中的单词:
wordList [word] = word.capitalize ()#我卡住了!
$ b返回.join(wordList)

else:返回data.capitalize()

else:返回数据

所以基本上,我想编辑这个项目,但我不知道该怎么做。

顺便说一句,这是一个可选的问题:在C#中我有机会调试我的代码,哟家伙在Python中使用调试? $ b

解决方案

使用列表理解:

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




如何在Python中调试?


print 的代码,交互式解释器的其他任何东西。我写了很多测试,并用鼻子运行。


I am new to python and I am trying to create a capitalize function that either capitalizes all words in a string or only the first word. Here is my function

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

So basically, I want to edit the item but I don't know how I can do it.

Btw, this is an optional question: in c# I had the chance to debug my code, what do yo guys use in python to debug?

解决方案

Use a list comprehension:

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

what do yo guys use in python to debug?

print statements for complicated pieces of code, the interactive interpreter for anything else. I write a lot of tests through, and run them with nose.

这篇关于如何在Python中编辑列表的每个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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