最近,我发现了一本书,书名为“用Python自动化那些无聊的东西”。我参加了一个练习,上面说
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with
and
inserted before the last item. For example, passing the previous spam list to the function would return'apples, bananas, tofu, and cats'
. But your function should be able to work with any list value passed to it.
我写了这段代码,但我相信有更好的方法。最简单的方法是什么
def list_manu(lst):
spam[-1] = 'and '+spam[-1]
new_spam=[]
x = ','.join(spam)
return f"'{x}'"
spam = ['apples', 'bananas', 'tofu','here','here', 'cats']
print(list_manu(spam))
您可以使用“and”连接最后两个元素,并使用逗号将其与前面的元素连接:
输出:
这个程序负责Oxford comma-
输出:
此程序不处理牛津逗号,但它适合您指定任务的目的-
输出:
相关问题 更多 >
编程相关推荐