目前正在通过这本初学者手册,完成了一个练习项目"逗号代码",要求用户构建一个程序:
将列表值作为参数,并返回一个字符串,其中所有项由逗号和空格分隔,并在最后一项之前插入.例如,将下面的垃圾邮件列表传递给该函数将返回"苹果,香蕉,豆腐和猫".但是您的函数应该能够处理传递给它的任何列表值.
spam = ['apples', 'bananas', 'tofu', 'cats']
Run Code Online (Sandbox Code Playgroud)
我对问题的解决方案(效果非常好):
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))
Run Code Online (Sandbox Code Playgroud)
我唯一的问题是,有什么方法可以缩短我的代码吗?或者让它更"pythonic"?
这是我的代码.
def listTostring(someList):
a = ''
for i in range(len(someList)-1):
a += str(someList[i])
a += str('and ' + someList[len(someList)-1])
print …Run Code Online (Sandbox Code Playgroud) python ×1