如何在python中创建一个遍历字符串列表的函数

问题描述

您好,我有一个包含以下字符串值的列表:

food = ['apples','bananas','tofu','pork']

我的任务是编写一个函数,该函数以列表值作为参数,并返回一个字符串,其中所有项目均以逗号和空格分隔,并在最后一项之前插入“ and”

我对此的解决方案是:

def formatList(food):
    result = ""
    for idx in food: 
        result += idx + "," + " "
    return result

如果我打印此调用函数,结果是:

print(formatList(food))
>> apples,bananas,tofu,pork,

预期的输出应该是:

print(formatList(food))
>> 'apples,and pork'

我该如何解决

解决方法

food = ['apples','bananas','tofu','pork']

def concat(food):
    return ",".join(food[:-1]) + " and " + food[-1]

print(concat(food))
## output 'apples,bananas,tofu and pork'
,

可以使用list的索引而不是for循环的list内容来完成此操作:

def formatList(food):
    result = ""
    for i in range(len(food)):
        if i == len(food)-1:
            result += f"and {food[i]}"
        else:
            result += f"{food[i]},"
    return result