【问题标题】:Adding comma's and and's between lists在列表之间添加逗号和和
【发布时间】:2018-03-31 18:08:40
【问题描述】:

如何在每个列表元素之间添加一个逗号,在最后两个元素之间添加一个“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 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

【问题讨论】:

  • 你得到了什么输出?

标签: python list code-formatting


【解决方案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

【讨论】:

  • 谢谢!我最初的代码与此类似,但不如您的干净。老师说可以改写3行。在我看来这是不可能的!你的回答已经帮助我理解我做错了什么!
【解决方案2】:

列表中只有一只猫的情况需要特殊处理。我要做的是,首先用逗号连接从索引 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)

【讨论】:

  • 谢谢!我已经有 2 个类似的解决方案,但我需要将输出放在单独的行中
  • @Denisuu 哦!那么 poke 的答案正是你所需要的。
  • 我也尝试了你的代码来理解它,但如果我只要求列表对象 0 ex: comma_and(cats[0]) 我得到:B、e、l、l 和一种。但是,当我执行 comma_and(cats[1]) 时它会起作用。
  • @Denisuu 它需要一个猫的列表作为输入,但是通过 cat[0] 你传递的是一只猫。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
相关资源
最近更新 更多