问题描述
我一直在经历自动化服装,并且遇到了一个名为逗号代码"的挑战(第4章).您必须编写一个函数,该函数需要一个列表并打印出一个字符串,用逗号将元素连接在一起,并在最后一个元素之前添加"and".
I've been going through Automatetheboringstuff and came across a challenge called Comma Code (end of chapter 4). You have to write a function that takes a list and print out a string, joining the elements with a comma and adding "and" before the last element.
请记住,我对python还是一个新手,或者对它进行编程,它仍然是可管理的任务,但是输出在插入的和"之前带有逗号.因此,我修改了代码以进行清理.这是我的代码:
Keeping in mind that I am fairly new to python, or programing for that matter, it was still a manageable task, but the output had a comma before the inserted "and". So I revised the code to clean that up. This is my code:
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.")
有更好的方法吗?是否有可以做到这一点的模块?
Is there a better way to do it? Is there a module that can do this?
推荐答案
您必须考虑只有一个元素的情况:
You'll have to account for the case where you have just the one element:
def comma_separator(sequence):
if not sequence:
return ''
if len(sequence) == 1:
return sequence[0]
return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1])
请注意,bool(sequence) is True
是测试非空列表的一种非常复杂的方法.只需使用if sequence:
就足够了,因为if
语句已查找布尔真值 .
Note that bool(sequence) is True
is a very elaborate way of testing for a non-empty list; simply using if sequence:
is enough as the if
statement looks for boolean truth already.
可以说,用序列以外的任何东西(可以被索引并且具有长度的东西)调用该函数只会导致异常.通常,您不测试此类函数中的类型.如果您必须测试类型,请使用isinstance(sequence, list)
至少允许有子类.
Arguably, calling the function with anything other than a sequence (something that can be indexed and has a length) should just result in an exception. You generally do not test for types in functions like these. If you did have to test for a type, use isinstance(sequence, list)
to at least allow for subclasses.
我也将传递空白列表设为错误.您可以将该异常转换为ValueError
:
I'd also make it an error to pass in an empty list. You could turn that exception into a ValueError
:
def comma_separator(sequence):
if len(sequence) > 1:
return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1])
try:
return sequence[0]
except IndexError:
raise ValueError('Must pass in at least one element')
后者的演示
>>> def comma_separator(sequence):
... if len(sequence) > 1:
... return '{} and {}'.format(', '.join(sequence[:-1]), sequence[-1])
... try:
... return sequence[0]
... except IndexError:
... raise ValueError('Must pass in at least one element')
...
>>> comma_separator(['foo', 'bar', 'baz'])
'foo, bar and baz'
>>> comma_separator(['foo', 'bar'])
'foo and bar'
>>> comma_separator(['foo'])
'foo'
>>> comma_separator([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in comma_separator
ValueError: Must pass in at least one element
这篇关于如何使用逗号有效地加入列表并添加“和".在最后一个元素之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!