Skip to main content
 首页 » 编程设计

python之如何在列表的最后一个元素之前添加 "and"

2025年05月04日23zengkefu

我正在制作这个程序,它需要打印出一个列表,如果列表更正确一点,我会更喜欢。我想知道是否可以在列表的最后一个元素之前添加一个“和”以使其看起来正确。谢谢。

  def inputEat(self): 
        input('What would you like to eat? Your choices are {}.'.format(', '.join(healthItems))) 
        Fighter.Health(x) 
        if self.health >= 100: 
            self.health = 100` 

请您参考如下方法:

你可以有一个函数来按照你想要的方式构造连接列表:

def join_and(items): 
    return ', '.join(items[:-1]) + ' and '+items[-1] 

即用逗号连接除最后一项以外的所有项,然后在最后一项之前添加“和”。 (请随意添加牛津逗号。)

>>> join_and(['alpha', 'beta', 'gamma']) 
'alpha, beta and gamma' 

如果您希望函数为长度为 1 或 0 的列表给出适当的结果,您可以这样做:

def join_and(items): 
    if len(items)==0: 
        return '' 
    if len(items)==1: 
        return items[0] 
    return ', '.join(items[:-1]) + ' and '+items[-1]