[英]Automate the Boring Stuff with Python - Comma Code
所以我想出了一個有效的解決方案,它不使用牛津逗號,有點麻煩,有沒有更干凈的方法來做到這一點?
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))`
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)
嘗試以下操作:-
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))
這本質上是@Azat Ibrakov 在單行中所擁有的,我只是在 python 中針對字符串操作警告againts +
。
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'
我的回答和第一篇文章!
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.