加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:41:21 所属栏目:Python 来源:网络整理
导读:目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,要求用户构建一个程序: 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
目前正在通过这本初学者手册,完成了一个练习项目“逗号代码”,要求用户构建一个程序:

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_string

print (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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读