在列表之间添加逗号和\ n和\ n

时间:2018-03-31 18:08:40

标签: python list code-formatting

如何在每个列表元素和"和"之间添加逗号。在最后2个之间,所以输出将是:

My cats are: Bella
My cats are: Bella and Tigger
My cats are: Bella, Tigger and Chloe
My cats are: Bella, Tigger, Chloe and Shadow

这里有我的两个功能,两个都不能正常工作:

Example = ['Bella', 'Tigger', 'Chloe', 'Shadow']

def comma_and(list):
    for i in range(len(list)):
        print('My Cats are:',', '.join(list[:i]), 'and', list[-1],)


def commaAnd(list):
    for i in range(len(list)):
        print('My Cats are:',', '.join(list[:i]), list.insert(-1, 'and'))

我目前的输出是:

>> comma_and(Example)
My Cats are:  and Shadow
My Cats are: Bella and Shadow
My Cats are: Bella, Tigger and Shadow
My Cats are: Bella, Tigger, Chloe and Shadow

>> commaAnd(Example)
My Cats are:  None
My Cats are: Bella None
My Cats are: Bella, Tigger None
My Cats are: Bella, Tigger, Chloe None

2 个答案:

答案 0 :(得分:1)

第一个解决方案几乎已经是你想要的了。您只需要确保不总是从列表中的最后一个元素(-1)获取当前迭代中的最后一个元素:

>>> for i in range(len(list)):
        print('My Cats are:',', '.join(list[:i]), 'and', list[i])

My Cats are:  and Bella
My Cats are: Bella and Tigger
My Cats are: Bella, Tigger and Chloe
My Cats are: Bella, Tigger, Chloe and Shadow

然后,当只有一个项目时,你只需要特殊情况下的第一次迭代:

>>> for i in range(len(list)):
        if i == 0:
            cats = list[0]
        else:
            cats = ', '.join(list[:i]) + ' and ' + list[i]
        print('My Cats are:', cats)


My Cats are: Bella
My Cats are: Bella and Tigger
My Cats are: Bella, Tigger and Chloe
My Cats are: Bella, Tigger, Chloe and Shadow

答案 1 :(得分:1)

列表中只有一只猫的情况需要特殊处理。我要做的是,首先用逗号连接从索引0到倒数第二个元素的列表元素。

', '.join(list[:-1])做了这一部分。值得注意的是,如果列表只有一只猫,那么list[:-1]将是一个空列表,因此', '.join(list[:-1])将是一个空字符串。所以,我只是利用这个空字符串来查明列表中是否只有一只猫。

def comma_and(list):
    cats = ', '.join(list[:-1])
    if cats:
        cats += ' and ' + list[-1]
    else:
        cats = list[0]
    print("My cats are: " + cats)