【问题标题】:"Comma Code" Program from Automate the Boring Stuff with Python来自用 Python 自动化无聊的东西的“逗号代码”程序
【发布时间】:2018-08-18 04:09:38
【问题描述】:

我正在通过 Al Sweigart 的“Automate the Boring Stuff with Python”一书学习 Python。我正在完成关于列表的一章,并且我有一个名为“逗号代码”的程序提示:

假设你有一个这样的列表值:

spam = ['apples', 'bananas', 'tofu', 'cats']

编写一个函数,该函数将列表值作为参数并返回一个字符串,其中所有项目由逗号和空格分隔,并在最后一项之前插入 。例如,将前一个垃圾邮件列表传递给函数将返回'apples, bananas, tofu, and cats'。但是您的函数应该能够处理传递给它的任何列表值。 "

到目前为止,这是我的代码:

def commaCode(newList):
   print(str(newList[:-1]) + 'and' + ' ' +  str(newList[-1]))
   return

nextlist = []
anotherlist = input('Enter a value')
while anotherlist != '':
   nextlist = nextlist + list(anotherlist)

commaCode(nextlist)

我觉得这应该可行,但每当我输入某种输入时,程序只会让我输入更多输入,但什么也没有发生。然后我尝试退出程序并询问是否要我“杀死程序”。我不确定我的代码有什么问题...我认为它可能与“while”语句有关,但我不确定如何解决它。

【问题讨论】:

  • 欢迎来到令人沮丧的编程世界。当你遇到这样的问题时,能够追踪它们是很重要的。我们称之为“调试”,这是最重要的开发技能之一。首先,请查看ericlippert.com/2014/03/05/how-to-debug-small-programs 的提示,了解如何追踪代码中的问题。

标签: python


【解决方案1】:

努力。您的函数相当接近,但您的 while 将无限运行,因为 anotherList 在循环块内永远不会更改。不过,nextlist 将在此循环中继续扩展,用户传递给input() 的任何字符串都会分解为字符。最终,程序会耗尽内存并崩溃。

不要相信我的话:print 应该在循环块内终止循环的变量,并查看它在每次通过时所做的事情(重要的调试技巧)。

有几种方法可以解决此问题。下面的方法允许用户在每个循环传递中输入输入,如果为空,则其结果要么breaks 循环,否则附加到用户输入的累积列表中。

def comma_code(items):
   return ', '.join(items[:-1]) + ' and ' + items[-1]

items = []

while 1:
    user_input = input('Enter a value: ')
    
    if user_input == '':
        break
    
    items.append(user_input)

print(comma_code(items))

示例运行:

Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 3
Enter a value: 4
Enter a value: 5
Enter a value:
1, 2, 3, 3, 4 and 5

请注意,根据Python coding standard,变量名称是snake_cased 而不是camelCased

我还删除了您的 commaCode 函数中的 print。这是一个side effect,通常不受欢迎,因为该功能不是多用途的:它只将内容打印到标准输出,不能提供太多其他功能。如果返回结果,调用者可以选择如何处理它(打印、反转、放入数据库……)。

另外请注意,如果用户没有输入任何内容或输入一个项目,则会分别出现崩溃或格式错误的输出。尝试将这些边缘情况作为练习来处理!

【讨论】:

  • 添加 and 应该以至少有两个元素为条件。
  • 另外,这个问题需要一个牛津逗号
【解决方案2】:

第二种方法是在程序中实际使用预定义列表上的函数。

spam = ['apples', 'bananas', 'tofu', 'cats']

otherlist = ['one', 'two', 'three', 'four', 'five']

def niceSentence(list):

    for item in list[:-1]:
        print(item + ", ", end='')

    print("and " + list[-1])

niceSentence(spam)

niceSentence(otherlist)

【讨论】:

    【解决方案3】:

    我以两种方式完成我的,每一种都包含您使用的步骤。两者都有效,但从不同来源获取列表输入。一个要求用户输入,就像你做的一样。但是,它实际上并没有定义函数;相反,程序就是功能。 (我在第 4 章中间的程序“allMyCats2.py”中模拟了这种方法。)

    anyList = []
    while True:
        print('Enter an item for your list, or hit enter to stop.')
        item = input()
        if item == '':
              break
        anyList = anyList + [item]
    
    for item in anyList[:-1]:
        print(item + ",", end='')
    
    print("and " + anyList[-1])
    

    【讨论】:

      【解决方案4】:

      这结合了两种方法:

      def niceSentence(list):
          for item in list[:-1]:
              print(item + ", ", end='')
          print("and " + list[-1])        #this defines the function that makes the comma list
      
      
      anyList = []
      
      while True:
          print('Enter an item for your list, or hit enter to stop.')
          item = input()
          if item == '':
                break
          anyList = anyList + [item]      #builds list from inputted strings
      
      niceSentence(anyList)  #calls function on built list
      

      【讨论】:

      • 以后,您可以编辑您的原始问题。您可能应该这样做并删除两个额外的。
      【解决方案5】:

      我做了这个简短的

      spam = ['apples', 'bananas', 'tofu', 'cats']
      
      def list_funk(theliste):
          for mot in theliste[:-1]: # first i work with index 0 to 3
              print(mot, end=', ')
          print('and ' + str(spam[-1])) # then adding what misses to complete exercise
      
      list_funk(spam)
      

      【讨论】:

        【解决方案6】:

        这是逗号代码练习项目问题的非常基本的方法。 答案是使用从书中获得的知识编写的,直到章节列表。不包含其他或高级概念。

        答案代码

        userInput=[]
        #Enter the number of total entries in the list
        n =int(input("Enter the number of input elements: "))
        for i in range(0,n):
            newInput=input() #This gets the list values
            userInput.append(newInput)
        
        #Function to execute the program
        def commaList(userInput):
            for i in range(len(userInput)):
                if i == len(userInput)-1:
                    print(' and '+userInput[i])
                else:
                    print(userInput[i], end=',')
            return
        commaList(userInput)
        

        例子

        #Console Screen:
        Enter the number of input elements: 4
        Maths
        Science
        History
        Music
        #ProgramOutput:
        Maths,Science,History, and Music
        

        我希望这会有所帮助。

        【讨论】:

          【解决方案7】:

          我首先声明了一个垃圾邮件列表,然后定义了 commaCode 函数。然后,我在列表的最后一项中添加了一个“和”,然后使用 for 循环在列表中最后一项之前的每个项中添加一个逗号。如果项目不是字符串数据类型,我将它们转换。

          因为我们想打印出包含所有项目的长字符串,所以我声明了一个空字符串变量 stringList,并使用 for 循环将所有项目附加到 stringList。

          最后,我打印出字符串列表。


          spam = ['apples', 'bananas', 'tofu', 'cats', 8, True]  #our list
          
          def commaCode(myList):
          
              myList[-1] = 'and ' + str(myList[-1])  #converted last element to string and 
                                                     #added an 'and'
              for i in range(len(myList)-1):    #add a comma to every element before
                  myList[i] = str(myList[i]) + ', '
          
              stringList = ''                 #declare an empty string variable
              for i in range(len(myList)):    #add each element to the string list
                  stringList = stringList + str(myList[i]) 
          
              print(stringList)               #print the entire string list
          
          commaCode(spam)
          

          【讨论】:

            【解决方案8】:

            这是我的答案。如果列表为空,则应打印“Nothing to see here”。一个包含一个项目的列表应该只打印那个项目,一个长度大于一个的列表应该产生所需的结果。希望这是正确的,不胜感激。

            spam = ['pizza','tofu','boats','hoes']
            
            
            
            
               def comma_code(values):
                    if len(values) < 1:
                        print('Nothing to see here.')
                    elif len(values) == 1:
                        print(values[0])
                    else:
                        print(', '.join(values[:-1]) + ' and ' + values[-1])
            
                comma_code(spam)
            

            【讨论】:

              【解决方案9】:
              def list_value(s):
                  while " " in s:
                      s.remove(" ")
                  while "" in s:
                      s.remove("")
                  return str(", ".join(s[:-1])) + " and " + str(s[-1])
              
              
              if __name__ == "__main__":
                  spam = ["apples", "bananas", "tofu", "cats"]
              
                  spam.append("manga")
                  spam.append("papayas")
                  spam.append("")
                  spam.append("citrus")
                  spam.append(" ")
                  spam.append("berries")
                  spam.append("melons")
                  spam.append("")
                  spam.append(" ")
                  spam.append(20)
                  fruits = list_value(spam)
              
                  print(fruits)
              

              【讨论】:

              • 不鼓励仅使用代码的答案。请简要说明您的答案如何解决问题,以及为什么它可能优于已提供的其他答案。
              猜你喜欢
              • 1970-01-01
              • 2017-09-13
              • 1970-01-01
              • 1970-01-01
              • 2020-05-14
              • 2019-10-18
              • 2020-08-30
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多