Python 添加逗号';s和';在列表之间切换
如何在每个列表元素之间添加逗号,在最后2个元素之间添加“and”,以便输出为:Python 添加逗号';s和';在列表之间切换,python,list,code-formatting,Python,List,Code Formatting,如何在每个列表元素之间添加逗号,在最后2个元素之间添加“and”,以便输出为: 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 com
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
列表中只有一只cat的情况需要特殊处理。我要做的是,首先用逗号将列表中的元素从索引0连接到最后一个元素 join(list[:-1])执行此部分。这里值得注意的一点是,如果列表只有一个cat,那么
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)
您得到了什么输出?谢谢!我已经有两个类似的解决方案,但我需要有单独的输出lines@Denisuu哦poke的答案正是您所需要的。我也尝试了您的代码来理解它,但如果我只要求列表对象0 ex:comma_和(cats[0]),则它无法正常工作,我得到:B,e,l,l和a。当我使用逗号_和(cats[1])时,它可以工作。@Denisuu它需要一个猫列表作为输入,但是通过传递cats[0]您就传递了一只猫。谢谢!我第一次使用的代码与此类似,但没有您的干净。老师说可以把它改写成三行。对我来说这似乎是不可能的!你的回答已经让我明白我做错了什么!