ATBSWP第4章实践项目:逗号代码

2024-05-19 07:58:00 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,实践项目如下:

假设您有这样一个列表值:spam = ['apples', 'bananas', 'tofu', 'cats'] 编写一个函数,该函数以列表值为参数,返回一个字符串,其中所有项用逗号和空格分隔,并在最后一项之前插入和。例如,将前面的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()和{}等等。在

链接-Chapter4


Tags: and项目函数字符串列表参数spamlist
3条回答

我就是这样解决问题的:

def commaCode(eggs):
    return ', '.join(map(str,eggs[:-1])) + ' and ' + str(eggs[-1])
spam = ['apples', 'bananas', 'tofu', 'cats']
print(commaCode(spam))

输出:

apples, bananas, tofu and cats

join()和map()在本章中没有讨论。我是在谷歌上搜索如何将列表转换成字符串的时候学会的。在

请尝试以下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)

以下是我对解决方案的看法。它利用了我们在这一章学到的一切。在

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])

相关问题 更多 >

    热门问题