所以我提出了一个有效的解决方案,通过一些小工具没有使用牛津逗号,是否有更清洁的方法来做到这一点?
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))`
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
请尝试以下方法: -
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))
答案 2 :(得分:0)
这基本上就是@Azat Ibrakov在单行中所拥有的内容,我只是警告了#{1}}在python中的字符串操作。
+
答案 3 :(得分:0)
我的答案和第一篇文章!
def returnString(list):
length = len(list)
i = 0
outputstring = list[i]
i += 1
while i < length - 1:
outputstring = outputstring + ', '+ str(list[i])
i = i + 1
outputstring = outputstring + ' and ' + list[i]
print(outputstring)
list = ['Ants', 'Spiders', 'Rabbits', 'Leopards', 'Lions', 'Tigers', 'Elephants']
returnString(list)
答案 4 :(得分:-1)