目前,我正在阅读这本初学者书籍,并完成了其中一个练习项目“逗号代码”,该项目要求用户构建一个程序,该程序:
将列表值作为参数并返回一个字符串,其中所有项目均以逗号和空格分隔,并插入到最后一项之前。例如,将 以下 垃圾邮件列表传递给该函数将返回“apples、bananas、tofu 和 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)
输出:苹果、香蕉、豆腐和猫
原文由 Sutharsan Sethurayar 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
str.join()
连接带有分隔符的字符串序列。如果你对 除 最后一个以外的所有单词都这样做,你可以插入' and '
代替:打破这个:
words[-1]
获取列表的最后一个元素。words[:-1]
对列表进行 切片 以生成一个新列表,其中包含 除 最后一个以外的所有单词。', '.join()
生成一个新字符串,所有参数字符串str.join()
加入', '
。如果输入列表中只有 一个 元素,则返回该元素,未连接。'{}, and {}'.format()
将逗号连接的单词和最后一个单词插入模板(用牛津逗号完成)。如果传入空列表,上述函数将引发
IndexError
异常;如果您觉得空列表是该函数的有效用例,则可以在函数中专门测试该情况。因此,上面将 除最后一个单词之外的所有单词 加入
', '
,然后将最后一个单词添加到结果中' and '
。请注意,如果只有一个词,您就得到那个词;在那种情况下没有什么可加入的。如果有两个,你会得到
'word1 and word 2'
。更多的话会产生'word1, word2, ... and lastword'
。演示: