【发布时间】:2015-08-14 11:15:11
【问题描述】:
我一直在经历Automatetheboringstuff 并遇到了一个名为逗号代码的挑战(chapter 4 的结尾)。您必须编写一个函数,该函数接受一个列表并打印出一个字符串,用逗号连接元素并在最后一个元素之前添加“and”。
请记住,我对 python 还是相当陌生,或者为此进行编程,这仍然是一项易于管理的任务,但输出在插入的“and”之前有一个逗号。所以我修改了代码来清理它。这是我的代码:
def comma_separator(someList):
"""The function comma_separator takes a list and joins it
into a string with (", ") and adds " and " before the last value."""
if type(someList) is list and bool(someList) is True:
return ", ".join(someList[:-1]) + " and " + someList[-1]
else:
print("Pass a non-empty list as the argument.")
有没有更好的方法呢?有没有可以做到这一点的模块?
【问题讨论】: