ATBSWP第4章实践项目:逗号代码 [英] ATBSWP Chapter 4 practice project: Comma Code
问题描述
因此,练习项目如下:
说您有一个像这样的列表值:spam = ['apples', 'bananas', 'tofu', 'cats']
编写一个函数,该函数以列表值作为参数,并返回一个字符串,其中所有项目均以逗号和空格分隔,并在最后一项之前插入并插入.例如,将先前的spam
列表传递给该函数将返回'apples, bananas, tofu, and cats'
.但是您的函数应该能够处理传递给它的任何列表值.
Say you have a list value like this: spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam
list to the function would return 'apples, bananas, tofu, and cats'
. But your function should be able to work with any list value passed to it.
到目前为止,我已经提出了这个建议:
So far I've come up with this:
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()
.
And of course the output is just the list values. I've tried to make line 5 as print(str(a_list))
, but that gives a syntax error. My line of thinking is that I have to change it to a string, but I'm lost. Am I missing something in the chapter? I've felt like I've gone over it several times. I feel like len(a_list)
should be somewhere in there but that would just give me a value of 5
. Any thoughts, or how I should go about thinking about this would be great help. I always feel like I'm really understanding this stuff and then I get to these practice projects and am ALWAYS confused on what to do. I know the practice projects are going to use some information we've learned in previous chapters and then focus mainly on the chapter we are on. Chapter 4 covers lists, list values, string values, tuples, copy.copy()
, and copy.deepcopy()
just to name a few.
链接-第4章
推荐答案
这是我对解决方案的看法.它利用了我们在本章中学到的所有知识.
Here's my take on the solution. It utilizes everything we have learned through this chapter.
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])
这篇关于ATBSWP第4章实践项目:逗号代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!