【问题标题】:Comma Code program in Automate the Boring Stuff自动化无聊的东西中的逗号代码程序
【发布时间】:2020-02-28 19:17:59
【问题描述】:

我正在尝试通过“使用 Python 自动化无聊的东西”来学习 Python。我目前在第4章。我目前正在尝试构建的实践项目如下:

假设你有一个这样的列表值: 垃圾邮件 = ['苹果','香蕉','豆腐','猫'] 编写一个函数,该函数将列表值作为参数并返回一个字符串,其中所有项目由逗号和空格分隔,并在最后一项之前插入并插入。例如,将先前的垃圾邮件列表传递给函数将返回“苹果、香蕉、豆腐和猫”。但是您的函数应该能够处理传递给它的任何列表值。

我试图在网上找到一些答案,但是网上的程序看起来和我写的很不一样。我想知道如何修复我的程序。目前它只将第一个列表项返回给我。这是我的代码:

randomlist = []
while True:
    print('Add something to the list: ')
    listitem = input()
    if listitem == '':
        break
    randomlist = randomlist + [listitem]

def commaplacer(somelist): #function
    for i in range(len(somelist)): #this reiterates the list
        if len(somelist)>i:
            return somelist[i]
        elif len(somelist)==i:
            return 'and' + somelist[i] 
        else:
            break

result = commaplacer(randomlist)
print(result)

【问题讨论】:

标签: python


【解决方案1】:

当您从一个函数return 时,这意味着您不希望它再运行。我认为您的 return 语句会导致它在您打算之前退出。

相反,我认为您应该将output 初始化为一个空字符串,然后在您浏览列表时构建它。在循环结束时,return output 将完成的字符串发回。

我认为您的循环逻辑可以简化为 2 种情况。该项目是列表中的最后一项len(somelist)-1 == i,我们需要添加'and',或者它不是最后一项,我们只需要放置一个逗号。

这是一个例子:

randomlist = ['Lions', 'tigers', 'bears, oh my!']


def commaplacer(somelist):  # function
    output = ''
    for i in range(len(somelist)):
        if len(somelist)-1 == i:
            output += 'and ' + somelist[i]
        else:
            output += somelist[i] + ', '
    return output


result = commaplacer(randomlist)
print(result)

会输出

Lions, tigers, and bears, oh my!

【讨论】:

  • 请原谅我的无知,但“输出”命令究竟是什么?我相信我还没有学会那个命令。谢谢你的回答!
  • 函数内部的output 只是一个在循环之前初始化的变量名,因此变量的作用域在循环的“外部”。然后,当您调用 output += 'and ' 或类似名称时,您将该信息附加到循环外的变量 output 中。您可以随意命名该变量。
  • 非常感谢。我还有一个问题。编辑:你为什么使用if len(somelist)-1 == i?而不仅仅是if len(somelist)==i 我有什么遗漏吗?
  • @Sami 想象一个somelist 有3 个项目,len(somelist) 将是3。但是,当我们遍历列表时,我们会访问列表中从0 开始的项目。列表中的 3 个值可通过 somelist[0]somelist[1]somelist[2] 访问。在上面的示例程序中,我们使用变量i 而不是特定的数字(即somelist[i]),但i 的值将是0,然后是1,最后是2i 永远不会等于 3,除非 somelist 有超过 3 个元素。
  • @Sami 简短的版本是我知道 Python 列表是零索引的,所以我知道 length-1 是列表中的最后一个元素。 Python、Java、C++、JavaScript 和许多其他语言都以这种方式工作(从 0 开始)。有一些语言,例如 FORTRAN,是从 1 开始的,所以无论您使用哪种语言编写代码,都需要注意这一点。
【解决方案2】:

您可以将代码合并到函数中的 3 行。

def commaplacer(somelist): #function
    if not somelist: return ''
    elif len(somelist) == 1: return somelist[0]
    else: return ', '.join(somelist[:-1])+', and ' + somelist[-1]

#line 1: check if list is empty. If yes, return empty string

#line 2: check if list has only one value. If yes, return only first value

#line 3: since list has more than one value, use 'join' function
#join all values until last one. add ', and ' then add last value

现在您可以调用该函数以获得所需的结果。

result = commaplacer(randomlist)
print(result)

结果将是:

#when you enter nothing, you get an empty string in return
>>> Add something to the list: 
>>> 
>>> 

#when you enter only one value to the list
>>> Add something to the list: 
>>> good
>>> 
>>> good

#when you enter a few values to the list

>>> Add something to the list: 
>>> apple
>>> Add something to the list: 
>>> banana
>>> Add something to the list: 
>>> carrot
>>> Add something to the list: 
>>> egg
Add something to the list: 

apple, banana, carrot, and egg

【讨论】:

    【解决方案3】:
    spam = []
    def coma(listName):
        output = ''
        for i in range(len(listName):
            if i==0:
                output = listName[i]
            elif i == len(listName) -1:
                output += ', and ' + listName[i]
            else:
                output += ', ' + listName[i]
        return output
    print(coma(spam))
    

    【讨论】:

    • 您的答案将通过edit 得到改进,以添加有关此答案如何改进现有的、已接受的答案的解释。
    • 如果我们在列表中有 [] 或单个值,我们也必须考虑这种情况,包括额外的 elif 语句。
    • @mabute,这与 WGriffing 已经提供的答案不一样
    • 如果您的列表只有一个值,我会尝试修改它,这样打印结果将没有不必要的逗号
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多