hebeer 2019-08-25 19:28 采纳率: 0%
浏览 168
已采纳

然后我编写了如下程序,求大神赐教错在哪里?

假定有下面这样的列表:
spam = ['apples', 'bananas', 'tofu', 'cats']

编写一个函数,它以一个列表值作为参数,返回一个字符串。该字符串包含所有表项,表项之间以逗
号和空格分隔,并在最后一个表项之前插入 and。例如,将前面的 spam 列表传递给函数,将返回
'apples, bananas, tofu, and cats'。但你的函数应该能够处理传递给它的任何列表。
————————————————
这是原题目,然后我编写了如下程序,求大神赐教错在哪里?

def change(spam):
    i = 0
    spell = spam[i]
    while True:
        i += 1
        spell = spell +', '+ spam[i]
        if i == len(spam):
            break
        return spell
spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs']
example=change(spam)
print(example)


返回的值,本应该是'apples, bananas, tofu, and cats'
```apples, bananas

  • 写回答

2条回答 默认 最新

  • threenewbee 2019-08-26 00:18
    关注
    # -*- coding: UTF-8 -*-
    def change(spam):
        i = 0
        spell = spam[i]
        while True:
            i += 1
            if len(spam) >= 2 and i == len(spam) - 1:
                spell = spell + ' and '     
            else:
                spell = spell +', '
            spell = spell + spam[i]
            if i == len(spam) - 1:
                break
        return spell
    spam = ['apples', 'bananas', 'tofu', 'cats', 'dogs']
    example=change(spam)
    print(example)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?