在最后一项之前用"和"将列表转换为逗号分隔的字符串 - Python 2.7

Sim*_*n S 12 python python-2.7

我创建了这个函数来解析列表:

listy = ['item1', 'item2','item3','item4','item5', 'item6']


def coma(abc):
    for i in abc[0:-1]:
        print i+',',
    print "and " + abc[-1] + '.'

coma(listy)

#item1, item2, item3, item4, item5, and item6.
Run Code Online (Sandbox Code Playgroud)

有没有更简洁的方法来实现这一目标?这适用于任何长度的列表.

Ult*_*nct 17

当列表中有1个以上的项目时(如果没有,只需使用第一个元素):

>>> "{} and {}".format(", ".join(listy[:-1]),  listy[-1])
'item1, item2, item3, item4, item5, and item6'
Run Code Online (Sandbox Code Playgroud)

编辑:如果你需要一个牛津逗号(不知道它甚至存在!) - 只需使用:", and"isntead.

  • @Daniel:完全没有意见.我的回答的焦点纯粹是`join(..)`和切片.OP应该能够处理空列表,一个项目列表(正如我在我的回答中所说),以及`.format(..)`. (2认同)

Cra*_*ler 5

def oxford_comma_join(l):
    if not l:
        return ""
    elif len(l) == 1:
        return l[0]
    else:
        return ', '.join(l[:-1]) + ", and " + l[-1]

print(oxford_comma_join(['item1', 'item2', 'item3', 'item4', 'item5', 'item6']))
Run Code Online (Sandbox Code Playgroud)

输出:

item1, item2, item3, item4, item5, and item6
Run Code Online (Sandbox Code Playgroud)

另外作为Pythonic的写作方式

for i in abc[0:-1]:
Run Code Online (Sandbox Code Playgroud)

for i in abc[:-1]:
Run Code Online (Sandbox Code Playgroud)