【发布时间】:2016-08-08 08:37:42
【问题描述】:
目前正在阅读这本初学者书籍,并完成了一个练习项目“逗号代码”,该项目要求用户构建一个程序:
将列表值作为参数并返回 一个字符串,所有项目用逗号和空格分隔,并 在最后一项之前插入。例如,将下面垃圾邮件列表传递给 该函数将返回“苹果、香蕉、豆腐和猫”。但是你的功能 应该能够处理传递给它的任何列表值。
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)
输出:苹果、香蕉、豆腐和猫
【问题讨论】:
-
如果你有工作代码,那么如果你想审查它,这感觉更适合codereview.stackexchange.com
-
请注意,您的代码不起作用列表中的最后一个字符串是任何早期元素的重复。
-
@EdChum 抱歉,不会再发生了,感谢您的提示。
-
@DanielRoseman 甚至没有意识到这一点,感谢您告诉我!
-
注意示例输出使用Oxford comma:
'apples, bananas, tofu, and cats',所以tofu后面有一个逗号。这让问题变得有点棘手......
标签: python