所以我想出了一个可行的解决方案,不使用牛津逗号,有没有一种更简洁的方法?
def stringy(spam):
output = ""
for thing in spam[:-1]:
output = output + thing + ", "
output = output[:-2] + " and " + spam[-1] #removes the last 2 chars
return output
spam = ['cats','cats','cats','cats', 'apples', 'bananas', 'tofu', 'cats']
print(stringy(spam))`发布于 2018-10-01 00:13:38
def list1(name):
name = name.insert(len(name)-1, 'and')
for i in range(len(spam)-2):
print(spam[i] ,end=', ' )
print(spam[-2], end=' ')
print(spam[-1],end='')
spam = ['apples', 'bananas', 'tofu', 'cats' , 'hello']
list1(spam)发布于 2018-06-04 19:07:36
尝试以下操作:-
def stringy(spam):
if len(spam) < 2:
return ' and '.join(spam)
else:
return ', '.join(spam[:-1]) + ' and '+spam[-1]
spams = [['cats','cats','cats','cats', 'apples', 'bananas', 'tofu', 'cats'],['tofu', 'cats'],[]]
for spam in spams:
print(stringy(spam))发布于 2018-06-04 19:37:46
这基本上就是@Azat Ibrakov在一行代码中所做的,我只想警告一下python中字符串操作的+。
def commanize(spam: list):
if len(spam) >= 2:
comma_str = ', '.join(spam[:-1])
return ' and '.join([comma_str, spam[-1]])
else:
return spam[0]
assert commanize(['a', 'b', 'c']) == 'a, b and c'
assert commanize(['a', 'b']) == 'a and b'
assert commanize(['a']) == 'a'https://stackoverflow.com/questions/50678693
复制相似问题