使用Python自动化无聊的东西:逗号代码

使用Python自动化无聊的东西:逗号代码,第1张

概述目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,要求用户构建一个程序: takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For exampl 目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,要求用户构建一个程序:

takes a List value as an argument and returns
a string with all the items separated by a comma and a space,with and
inserted before the last item. For example,passing the below spam List to
the function would return ‘apples,bananas,tofu,and cats’. But your function
should be able to work with any List value passed to it.

spam = ['apples','bananas','tofu','cats']

我对问题的解决方案(效果非常好):

spam= ['apples','cats']def List_thing(List):    new_string = ''    for i in List:        new_string = new_string + str(i)        if List.index(i) == (len(List)-2):            new_string = new_string + ',and '        elif List.index(i) == (len(List)-1):            new_string = new_string        else:            new_string = new_string + ','    return new_stringprint (List_thing(spam))

我唯一的问题是,有什么方法可以缩短我的代码吗?或者让它更“pythonic”?

这是我的代码.

def ListTostring(someList):    a = ''    for i in range(len(someList)-1):        a += str(someList[i])    a += str('and ' + someList[len(someList)-1])    print (a)spam = ['apples','cats']ListTostring(spam)

产量:苹果,香蕉,豆腐和猫

解决方法 使用str.join()连接带有分隔符的字符串序列.如果你对除了最后一个之外的所有单词都这样做,你可以在那里插入’和’:

def List_thing(words):    if len(words) == 1:        return words[0]    return '{},and {}'.format(','.join(words[:-1]),words[-1])

打破这个:

> words [-1]获取列表的最后一个元素.单词[: – 1]将列表切片以生成包含除最后一个单词之外的所有单词的新列表.
>’,’.join()生成一个新字符串,str.join()的所有参数字符串都与’,’连接.如果输入列表中只有一个元素,则返回该元素,取消连接.
>'{}和{}’.format()将逗号连接的单词和最后一个单词插入模板(以牛津逗号填写).

如果传入一个空列表,上面的函数将引发一个IndexError异常;如果您觉得空列表是函数的有效用例,您可以在函数中专门测试该情况.

所以上面用’,’连接除了最后一个单词之外的所有单词,然后用’和’将最后一个单词添加到结果中.

请注意,如果只有一个单词,则会得到一个单词;在这种情况下没有什么可以加入的.如果有两个,你得到’word1和word 2′.更多的单词产生’word1,word2,…和lastword’.

演示:

>>> def List_thing(words):...     if len(words) == 1:...         return words[0]...     return '{},words[-1])...>>> spam = ['apples','cats']>>> List_thing(spam[:1])'apples'>>> List_thing(spam[:2])'apples,and bananas'>>> List_thing(spam[:3])'apples,and tofu'>>> List_thing(spam)'apples,and cats'
总结

以上是内存溢出为你收集整理的使用Python自动化无聊的东西:逗号代码全部内容,希望文章能够帮你解决使用Python自动化无聊的东西:逗号代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1195240.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存