我目前正在学习这本入门书籍,并完成了一个名为“逗号代码”的练习项目,该项目要求用户构建一个程序,其功能如下:
将列表作为参数传递给函数,并返回一个字符串,其中所有项都用逗号和空格分隔,最后一项前插入“and”。例如,将下面的 spam 列表传递给函数将返回'apples,bananas,tofu,and cats'。但是您的函数应能够处理传递给它的任何列表值。
spam = ['apples', 'bananas', 'tofu', 'cats']
我对这个问题的解决方案(已完美运行):
spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
new_string = ''
for i in list:
new_string = new_string + str(i)
if list.index(i) == (len(list)-2):
new_string = new_string + ', and '
elif list.index(i) == (len(list)-1):
new_string = new_string
else:
new_string = new_string + ', '
return new_string
print (list_thing(spam))
我唯一的问题是是否有办法缩短我的代码?或者让它更符合'Pythonic'的风格?
以下是我的代码。
def listTostring(someList):
a = ''
for i in range(len(someList)-1):
a += str(someList[i])
a += str('and ' + someList[len(someList)-1])
print (a)
spam = ['apples', 'bananas', 'tofu', 'cats']
listTostring(spam)
输出:苹果,香蕉,豆腐和猫