首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Python - Comma Code自动化那些无聊的东西

用Python - Comma Code自动化那些无聊的东西
EN

Stack Overflow用户
提问于 2018-06-04 18:40:04
回答 5查看 473关注 0票数 1

所以我想出了一个可行的解决方案,不使用牛津逗号,有没有一种更简洁的方法?

代码语言:javascript
复制
def stringy(spam):
    output = ""
    for thing in spam[:-1]: 
        output = output + thing + ", "
    output = output[:-2] + " and " + spam[-1] #removes the last 2 chars 
    return output

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

print(stringy(spam))`
EN

回答 5

Stack Overflow用户

发布于 2018-10-01 00:13:38

代码语言:javascript
复制
def list1(name):
    name = name.insert(len(name)-1, 'and')
    for i in range(len(spam)-2):

        print(spam[i] ,end=', ' )
    print(spam[-2], end=' ')    
    print(spam[-1],end='')



spam = ['apples', 'bananas', 'tofu', 'cats' , 'hello']
list1(spam)
票数 1
EN

Stack Overflow用户

发布于 2018-06-04 19:07:36

尝试以下操作:-

代码语言:javascript
复制
def stringy(spam):
    if len(spam) < 2:
        return ' and '.join(spam)
    else:
        return ', '.join(spam[:-1]) + ' and '+spam[-1]

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

for spam in spams:
    print(stringy(spam))
票数 0
EN

Stack Overflow用户

发布于 2018-06-04 19:37:46

这基本上就是@Azat Ibrakov在一行代码中所做的,我只想警告一下python中字符串操作的+

代码语言:javascript
复制
def commanize(spam: list):
    if len(spam) >= 2:
        comma_str = ', '.join(spam[:-1])
        return ' and '.join([comma_str, spam[-1]])
    else:
        return spam[0]

assert commanize(['a', 'b', 'c'])  == 'a, b and c'
assert commanize(['a', 'b'])  == 'a and b'
assert commanize(['a'])  == 'a'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50678693

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档