如何在每个列表元素之间添加逗号,并在最后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
最佳答案
第一个解决方案几乎已经是您想要的。您只需确保不总是从列表(-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
关于python - 在列表之间添加逗号和和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49590863/