Python 是否有更好的方法来完成此功能?
最近我发现了一本书,名为《用Python自动化无聊的东西》。我参加了一个练习,上面说 编写一个函数,将列表值作为参数并返回 字符串,所有项目由逗号和空格分隔,带和 插入到最后一项之前。例如,传递以前的垃圾邮件 函数的列表将返回“苹果、香蕉、豆腐和猫”。 但是您的函数应该能够处理传递给的任何列表值 它 我写了这段代码,但我相信有更好的方法。最简单的方法是什么Python 是否有更好的方法来完成此功能?,python,python-3.x,Python,Python 3.x,最近我发现了一本书,名为《用Python自动化无聊的东西》。我参加了一个练习,上面说 编写一个函数,将列表值作为参数并返回 字符串,所有项目由逗号和空格分隔,带和 插入到最后一项之前。例如,传递以前的垃圾邮件 函数的列表将返回“苹果、香蕉、豆腐和猫”。 但是您的函数应该能够处理传递给的任何列表值 它 我写了这段代码,但我相信有更好的方法。最简单的方法是什么 def list_manu(lst): spam[-1] = 'and '+spam[-1] new_spam=[] x =
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))
这个程序负责- 输出:
'apples, bananas, tofu, here, here, and cats'
'apples, bananas, tofu, here, here, and cats'
此程序不处理牛津逗号,但它适合给定任务的目的-
def list_manu(spam):
if len(spam) == 1:
return f"'{spam[0]}'"
body = ", ".join(map(str, spam[:-1]))
return f"'{body}, and {spam[-1]}'"
spam = ['apples', 'bananas', 'tofu', 'here', 'here', 'cats']
print(list_manu(spam))
输出:
'apples, bananas, tofu, here, here, and cats'
'apples, bananas, tofu, here, here, and cats'
可以使用and连接最后两个元素,并使用逗号将其与前面的元素连接:
# without Oxford comma (e.g. French punctuation)
def list_manu(lst):
return ", ".join(lst[:-2]+[" and ".join(lst[-2:])])
# with Oxford comma (uses ', and ' when size is 3+)
def list_manu(lst):
return ", ".join(lst[:-2]+[", and "[len(lst)<3:].join(lst[-2:])])
哇,谢谢lot@seprico没问题!我已经编辑了我的答案,包括了更多的细节,请查看。它们都很棒,谢谢。这看起来更容易理解