题目要求输入一个列表,输出用“,”分隔的列表元素,最后一个元素前面要加上“and ”。
代码示例:
# 定义函数
def comma_code(list):
if len(list) == 0:
return ''
elif len(list) == 1:
return str(list[0])
elif len(list) == 2:
return str(list[0]) + ' and ' + str(list[1])
else:
result = ''
for i in range(len(list)-1):
result += str(list[i]) + ', '
result += 'and ' + str(list[-1])
return result
# 测试
spam = ['apples', 'bananas', 'tofu', 'cats']
print(comma_code(spam)) # 输出: 'apples, bananas, tofu, and cats'