因此,实践项目如下:
假设你有一个这样的列表值:spam = ['apples', 'bananas', 'tofu', 'cats']写一个函数,它接受一个列表值作为参数,并返回一个字符串,所有项都用逗号和空格分隔,并在最后一项之前插入and。例如,将前面的spam列表传递给函数将返回'apples, bananas, tofu, and cats'。但是您的函数应该能够处理传递给它的任何列表值。
到目前为止,我已经想出了这个:
spam = ['apples', 'bananas', 'tofu', 'cats']
def commacode(a_list):
a_list.insert(-1, 'and')
print(a_list)
commacode(spam)当然,输出只是列表值。我尝试将第5行设置为print(str(a_list)),但这给出了一个语法错误。我的想法是,我必须将其更改为字符串,但我迷路了。这一章我是不是漏掉了什么?我觉得我已经复习过好几次了。我觉得len(a_list)应该在其中的某个地方,但这只会给我一个5的值。任何想法,或者我应该如何思考这一点都将是非常有帮助的。我总是觉得我真的理解了这些东西,然后我进入了这些实践项目,总是对该做什么感到困惑。我知道练习项目将使用我们在前几章中学到的一些信息,然后主要集中在我们所在的章节。第4章介绍了列表、列表值、字符串值、元组、copy.copy()和copy.deepcopy()。
链接- Chapter4
发布于 2018-03-31 04:19:22
这就是我解决这个问题的方法:
def commaCode(eggs):
return ', '.join(map(str,eggs[:-1])) + ' and ' + str(eggs[-1])
spam = ['apples', 'bananas', 'tofu', 'cats']
print(commaCode(spam))输出:
苹果,香蕉,豆腐和猫
join()和map()在本章中没有讨论。我是在谷歌搜索如何将列表转换为字符串时学会的。
发布于 2018-09-26 10:20:17
以下是我对解决方案的看法。它利用了我们在本章中学到的所有知识。
def pr_list(listothings):
for i in range(len(listothings)-1):
print(listothings[i] + ', ', end='')
spam = ['apples', 'bananas', 'tofu', 'cats']
pr_list(spam)
print('and ' + spam[-1])发布于 2016-06-12 15:52:12
尝试以下commacode函数:
monty = ['apples', 'bananas', 'tofu', 'cats', 'dogs', 'pigs']
def commacode(listname):
listname[len(listname) - 1] = 'and ' + listname[len(listname) - 1]
index = 0
new_string = listname[index]
while index < len(listname) - 1:
new_string = new_string + ', ' + listname[index + 1]
index = index + 1
if index == len(listname) - 1:
print(new_string)
commacode(monty)https://stackoverflow.com/questions/36191668
复制相似问题