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

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型