【问题标题】:Automate the boring stuff with Python: Comma Code用 Python 自动化无聊的东西:逗号代码
【发布时间】:2016-08-08 08:37:42
【问题描述】:

目前正在阅读这本初学者书籍,并完成了一个练习项目“逗号代码”,该项目要求用户构建一个程序:

将列表值作为参数并返回 一个字符串,所有项目用逗号和空格分隔,并 在最后一项之前插入。例如,将下面垃圾邮件列表传递给 该函数将返回“苹果、香蕉、豆腐和猫”。但是你的功能 应该能够处理传递给它的任何列表值。

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

我对问题的解决方案(效果很好):

spam= ['apples', 'bananas', 'tofu', 'cats']
def list_thing(list):
    new_string = ''
    for i in list:
        new_string = new_string + str(i)
        if list.index(i) == (len(list)-2):
            new_string = new_string + ', and '
        elif list.index(i) == (len(list)-1):
            new_string = new_string
        else:
            new_string = new_string + ', '
    return new_string

print (list_thing(spam))

我唯一的问题是,有什么办法可以缩短我的代码吗?或者让它更“pythonic”?

这是我的代码。

def listTostring(someList):
    a = ''
    for i in range(len(someList)-1):
        a += str(someList[i])
    a += str('and ' + someList[len(someList)-1])
    print (a)

spam = ['apples', 'bananas', 'tofu', 'cats']
listTostring(spam)

输出:苹果、香蕉、豆腐和猫

【问题讨论】:

  • 如果你有工作代码,那么如果你想审查它,这感觉更适合codereview.stackexchange.com
  • 请注意,您的代码不起作用列表中的最后一个字符串是任何早期元素的重复。
  • @EdChum 抱歉,不会再发生了,感谢您的提示。
  • @DanielRoseman 甚至没有意识到这一点,感谢您告诉我!
  • 注意示例输出使用Oxford comma'apples, bananas, tofu, and cats',所以tofu后面有一个逗号。这让问题变得有点棘手......

标签: python


【解决方案1】:

使用str.join() 连接带有分隔符的字符串序列。如果您对最后一个 除了 的所有单词都这样做,则可以在其中插入 ' and '

def list_thing(words):
    if len(words) == 1:
        return words[0]
    return '{}, and {}'.format(', '.join(words[:-1]), words[-1])

分解:

  • words[-1] 获取列表的最后一个元素。 words[:-1] 切片列表以生成一个新列表,其中包含所有单词除了最后一个。

  • ', '.join() 生成一个新字符串,str.join() 的所有参数字符串都与', ' 连接。如果输入列表中只有 一个 元素,则返回该元素,未加入。

  • '{}, and {}'.format() 将逗号连接的单词和最后一个单词插入到模板中(使用牛津逗号完成)。

如果传入一个空列表,上述函数将引发IndexError异常;如果您认为空列表是该函数的有效用例,则可以在该函数中专门测试该案例。

所以上面将 除了最后一个单词之外的所有单词', ' 连接起来,然后将最后一个单词与' and ' 添加到结果中。

请注意,如果只有一个词,你会得到那个词;在这种情况下没有什么可加入的。如果有两个,你会得到'word1 and word 2'。更多的词产生'word1, word2, ... and lastword'

演示:

>>> def list_thing(words):
...     if len(words) == 1:
...         return words[0]
...     return '{}, and {}'.format(', '.join(words[:-1]), words[-1])
...
>>> spam = ['apples', 'bananas', 'tofu', 'cats']
>>> list_thing(spam[:1])
'apples'
>>> list_thing(spam[:2])
'apples, and bananas'
>>> list_thing(spam[:3])
'apples, bananas, and tofu'
>>> list_thing(spam)
'apples, bananas, tofu, and cats'

【讨论】:

  • 我猜你在创建单元测试方面一定是个野兽;)(顺便说一句:空列表呢?)
  • @Cyrbil:忽略那个;这是一个错误,应该是。
  • 吹毛求疵:我不认为牛津逗号放在“苹果和香蕉”之类的句子中。
  • @bereal:那么这是原始作业的问题,它没有指定任何此类要求。
  • @aurumpurum 实际上,我非常不同意:将您的参数转换为正确的类型是调用者需要负责的事情。而且空列表不是一个句子,我在之前的评论中提到我觉得应该提出一个例外,并且在我的回答中也明确说明了这一点。
【解决方案2】:

我使用了不同的方法。我是初学者,所以我不知道这是否是最干净的方法。对我来说,这似乎是最简单的方法:

spam = ['apples', 'pizza', 'dogs', 'cats']

def comma(items):
    for i in range(len(items) -2):
        print(items[i], end=", ")# minor adjustment from one beginner to another: to make it cleaner, simply move the ', ' to equal 'end'. the print statement should finish like this --> end=', '
    print(items[-2] + 'and ' + items[-1]) 

comma(spam)

这将给出输出:

apples, pizza, dogs and cats

【讨论】:

  • 我认为,这是一个非常可靠的初学者方法,尤其是当您使用从书中学到的代码时,但项目确实说它应该与传递给的任何列表值一起使用它。如果我只有spam = ['apples'],列表索引将超出范围。
  • 另外,赋值语句说函数需要返回一个字符串。你的函数返回None
【解决方案3】:

这是一个正确处理Oxford comma 的解决方案。它还处理一个空列表,在这种情况下它返回一个空字符串。

def list_thing(seq):
    return (' and '.join(seq) if len(seq) <= 2
        else '{}, and {}'.format(', '.join(seq[:-1]), seq[-1]))

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

for i in range(1 + len(spam)):
    seq = spam[:i]
    s = list_thing(seq)
    print(i, seq, repr(s))

输出

0 [] ''
1 ['apples'] 'apples'
2 ['apples', 'bananas'] 'apples and bananas'
3 ['apples', 'bananas', 'tofu'] 'apples, bananas, and tofu'
4 ['apples', 'bananas', 'tofu', 'cats'] 'apples, bananas, tofu, and cats'

FWIW,这是一个使用 if-else 语句而不是条件表达式的更易读的版本:

def list_thing(seq):
    if len(seq) <= 2:
        return ' and '.join(seq)
    else:
        return '{}, and {}'.format(', '.join(seq[:-1]), seq[-1])    

这是一个可读性稍差的版本,使用 f 字符串:

def list_thing(seq):
    if len(seq) <= 2:
        return ' and '.join(seq)
    else:
        return f"{', '.join(seq[:-1])}, and {seq[-1]}"   

请注意,Martijn 的代码从 2 项列表中生成 'apples, and bananas'。我的回答在语法上更正确(用英语),但 Martijn 的回答在技术上更正确,因为它完全符合 OP 引用中指定的内容(尽管我不同意他对空列表的处理)。

【讨论】:

    【解决方案4】:

    我试过了,希望这是你要找的:-

    spam= ['apples', 'bananas', 'tofu', 'cats']
    
    def list_thing(list):
    
    #creating a string then splitting it as list with two items, second being last word
        new_string=', '.join(list).rsplit(',', 1)    
    
    #Using the same method used above to recreate string by replacing the separator.
    
        new_string=' and'.join(new_string)
        return new_string
    
    print(list_thing(spam))
    

    【讨论】:

    • 使用list 作为变量名不是一个好主意,因为它会影响内置的list 类型。它不会在这里造成问题,但它确实会使代码对其他读者有点困惑,并且它可能导致神秘的错误。
    • 我完全同意你的看法。虽然使用“列表”作为变量名并不是我的意图。我只是根据我的理解修改有问题的代码,保留问题中提到的变量名,只是为了解释这个概念。跨度>
    【解决方案5】:

    我对这个问题的解释是,单个列表项也将是最后一个列表项,因此需要在其前面插入“和”,以及返回两个都带有“, and”的两项列表' 它们之间。因此无需单独处理单个或两个项目列表,只需前 n 个项目和最后一个项目。 我还要注意,虽然很好,但当学生遇到这个问题时,许多其他项目使用 Automate the Boring Stuff 文本中没有教授的模块和功能(像我这样的学生已经看过 join.format其他地方,但试图只使用文本中教过的内容)。

    def commacode(passedlist):
        stringy = ''
        for i in range(len(passedlist)-1):
            stringy += str(passedlist[i]) + ', '
            # adds all except last item to str
        stringy += 'and ' + str(passedlist[len(passedlist)-1])
        # adds last item to string, after 'and'
        return stringy
    

    您可以通过以下方式处理空列表情况:

    def commacode(passedlist):
        stringy = ''
        try:
            for i in range(len(passedlist)-1):
                stringy += str(passedlist[i]) + ', '
                # adds all except last item to str
            stringy += 'and ' + str(passedlist[len(passedlist)-1])
            # adds last item to string, after 'and'
            return stringy
        except IndexError:
            return '' 
            #handles the list out of range error for an empty list by returning ''
    

    【讨论】:

      【解决方案6】:

      其他人已经给出了很好的单行解决方案,但是改进您的实际实现的一个好方法 - 并解决它在元素重复时不起作用的事实 - 是在 for 循环中使用 enumerate 来跟踪索引,而不是使用index,它总是找到目标的第一次

      for counter, element in enumerate(list):
          new_string = new_string + str(element)
          if counter == (len(list)-2):
              ...
      

      【讨论】:

        【解决方案7】:

        格式语句更简洁。

        这对我也有用:

        def sentence(x):
            if len(x) == 1:
                return x[0]
            return (', '.join(x[:-1])+ ' and ' + x[-1])
        

        【讨论】:

        • 吹毛求疵:', and '
        【解决方案8】:

        由于该函数必须适用于传递给它的所有列表值,包括整数,因此它应该能够返回/打印所有值,即作为 str()。我的完整工作代码如下所示:

        spam = ['apples', 'bananas', 'tofu', 'cats', 2]
        
        def commacode(words):
        
            x = len(words)
        
            if x == 1:
                print(str(words[0]))
            else:
                for i in range(x - 1):
                    print((str(words[i]) + ','), end=' ')
                print(('and ' + str(words[-1])))
        
        commacode(spam)
        

        【讨论】:

          【解决方案9】:

          只是一个简单的代码。我认为我们不需要在这里使用任何花哨的东西。 :p

          def getList(list):
              value = ''
              for i in range(len(list)):
                  if i == len(list) - 1:
                      value += 'and '+list[i]
                  else:
                      value += list[i] + ', '
              return value
          
          spam = ['apples', 'bananas', 'tofu', 'cats']
          
          print('### TEST ###')
          print(getList(spam))
          

          【讨论】:

          • 我认为这是最干净的解决方案。
          • 但是,如果我这样做spam = ['apples'],输出会给我and apples
          【解决方案10】:

          没有循环,没有连接,只有两个打印语句:

          def commalist(listname):
              print(*listname[:-1], sep = ', ',end=", "),
              print('and',listname[-1])
          

          【讨论】:

            【解决方案11】:

            我正在阅读同一本书并提出了以下解决方案: 这允许用户输入一些值并根据输入创建一个列表。

            userinput = input('Enter list items separated by a space.\n')
            userlist = userinput.split()
            
            def mylist(somelist):
                for i in range(len(somelist)-2): # Loop through the list up until the second from last element and add a comma
                    print(somelist[i] + ', ', end='')
                print(somelist[-2] + ' and ' + somelist[-1]) # Add the last two elements of the list with 'and' in-between them
            
            mylist(userlist)
            

            例子:

            用户输入:一二三四五 输出:一、二、三、四、五

            【讨论】:

              【解决方案12】:

              这就是我想出的。可能有一种更简洁的方法来编写它,但是只要列表中至少有一个元素,这应该适用于任何大小的列表。

              spam = ['apples', 'oranges' 'tofu', 'cats']
              def CommaCode(list):
                  if len(list) > 1 and len(list) != 0:
                      for item in range(len(list) - 1):
                          print(list[item], end=", ")
                      print('and ' + list[-1])
                  elif len(list) == 1:
                      for item in list:
                          print(item)
                  else:
                      print('List must contain more than one element')
              CommaCode(spam)
              

              【讨论】:

                【解决方案13】:
                def sample(values):
                    if len(values) == 0:
                         print("Enter some value")
                    elif len(values) == 1:
                        return values[0]
                    else:
                        return ', '.join(values[:-1] + ['and ' + values[-1]])
                
                spam = ['apples', 'bananas', 'tofu', 'cats']
                print(sample(spam))
                

                【讨论】:

                  【解决方案14】:
                  listA = [ 'apples', 'bananas', 'tofu' ]
                  def commaCode(listA):
                      s = ''
                      for items in listA:
                          if items == listA [0]:
                              s = listA[0]
                          elif items == listA[-1]:
                              s += ', and ' + items
                          else:
                              s += ', ' + items
                      return s
                  print(commaCode(listA))
                  

                  【讨论】:

                    【解决方案15】:

                    我是一个相当新的pythonista。在问题中,有人要求该函数以本论坛中其他解决方案“打印”它的格式将列表内容作为字符串返回。以下是(在我看来)这个问题的更清洁的解决方案。

                    这说明了 Automate The Boring Stuff 中第 4 章 [Lists] 的逗号代码解决方案。

                    def comma_code(argument):
                    
                        argument_in_string = ''
                        argument_len = len(argument)
                        for i in range(argument_len):
                            if i == (argument_len - 1):
                                argument_in_string = argument_in_string + 'and ' + argument[i]
                                return argument_in_string
                    
                            argument_in_string = argument_in_string + argument[i] + ', '
                    
                    spam = ['apples', 'bananas', 'tofu', 'cats']
                    return_value = comma_code(spam)
                    print(return_value)"
                    

                    【讨论】:

                      【解决方案16】:

                      我想出了这个解决方案

                      #This is the list which needs to be converted to String
                      spam = ['apples', 'bananas', 'tofu', 'cats']
                      
                      #This is the empty string in which we will append
                      s = ""
                      
                      
                      def list_to_string():
                          global spam,s
                          for x in range(len(spam)):
                              if s == "":
                                  s += str(spam[x])
                              elif x == (len(spam)-1):
                                  s += " and " + str(spam[x])
                              else:
                                  s += ", " + str(spam[x])
                          return s
                      
                      a = list_to_string()
                      print(a)
                      

                      【讨论】:

                        【解决方案17】:

                        由于没有提到,这里有一个f字符串的答案,供参考:

                        def list_things(my_list):
                            print(f'{", ".join(my_list[:-1])} and {my_list[-1]}.')
                        

                        插入自定义消息并接受字符串作为参数的示例:

                        def like(my_animals = None):
                            message = 'The animals I like the most are'
                            if my_animals == None or my_animals == '' or len(my_animals) == 0:
                                return 'I don\'t like any animals.'
                            elif len(my_animals) <= 1 or type(my_animals) == str:
                                return f'{message} {my_animals if type(my_animals) == str else my_animals[0]}.'
                            return f'{message} {", ".join(my_animals[:-1])} and {my_animals[-1]}.'
                        
                        
                        >>> like()
                        >>> like('')
                        >>> like([])
                        # 'I don't like any animals.'
                        
                        >>> like('unicorns') 
                        >>> like(['unicorns']) 
                        # 'The animals I like the most are unicorns.'
                        
                        >>> animals = ['unicorns', 'dogs', 'rabbits', 'dragons']
                        >>> like(animals) 
                        # 'The animals I like the most are unicorns, dogs, rabbits and dragons.'
                        

                        【讨论】:

                          【解决方案18】:

                          我对任何解决方案都不满意,因为没有人处理or 的情况,例如apples, bananas, or berries

                          def oxford_comma(words, conjunction='and'):
                              conjunction = ' ' + conjunction + ' '
                          
                              if len(words) <= 2:
                                  return conjunction.join(words)
                              else:
                                  return '%s,%s%s' % (', '.join(words[:-1]), conjunction, words[-1])
                          

                          否则,此解决方案与@PM2Ring 提供的解决方案或多或少相同

                          【讨论】:

                            【解决方案19】:

                            无论列表中的数据类型是什么,boolean、int、string、float 等,此代码都有效。

                            def commaCode(spam):
                                count = 0
                                max_count = len(spam) - 1
                            
                                for x in range(len(spam)):
                                    if count < max_count:
                                        print(str(spam[count]) + ', ', end='')
                                        count += 1
                                    else:
                                        print('and ' + str(spam[max_count]))
                            
                            spam1 = ['cat', 'bananas', 'tofu', 'cats']
                            spam2 = [23, '', True, 'cats']
                            spam3 = []
                            
                            commaCode(spam1)
                            commaCode(spam2)
                            commaCode(spam3)
                            

                            【讨论】:

                              【解决方案20】:
                              def listall(lst):               # everything "returned" is class string
                                  if not lst:                 # equates to if not True. Empty container is always False
                                      return 'NONE'           # empty list returns string - NONE
                                  elif len(lst) < 2:          # single value lists
                                      return str(lst[0])      # return passed value as a string (do it as the element so 
                                                              #  as not to return [])
                                  return (', '.join(str(i) for i in lst[:-1])) + ' and ' + str(lst[-1])
                                      # joins all elements in list sent, up to last element, with (comma, space) 
                                      # AND coverts all elements to string. 
                                      # Then inserts "and". lastly adds final element of list as a string.
                              

                              这不是为了回答最初的问题。这是为了展示如何定义解决本书要求的所有问题的函数,而不是复杂的。我认为这是可以接受的,因为原始问题发布了书籍“逗号代码”测试。 重要提示我发现一些可能对其他人有所帮助的困惑。 “列表值”是指列表类型的值或“整个列表”,而不是“类型列表”中的单个值(或切片)。希望对您有所帮助

                              这是我用来测试它的样本:

                              empty = []
                              ugh = listall(empty)
                              print(type(ugh))
                              print(ugh)
                              test = ['rabbits', 'dogs', 3, 'squirrels', 'numbers', 3]
                              ughtest = listall(test)
                              print(type(ughtest))
                              print(ughtest)
                              supertest = [['ra', 'zues', 'ares'],
                                          ['rabbit'],
                                          ['Who said', 'biscuits', 3, 'or', 16.71]]
                              one = listall(supertest[0])
                              print(type(one))
                              print(one)
                              two = listall(supertest[1])
                              print(type(two))
                              print(two)
                              last = listall(supertest[2])
                              print(type(last))
                              print(last)
                              
                              

                              【讨论】:

                                【解决方案21】:

                                为了简单,海因获胜。

                                仅,作者指定:

                                “您的函数应该能够处理传递给它的任何列表值。”

                                要伴随非字符串,请将@​​987654321@ 标签添加到所有 [i] 函数。

                                spam = ['apples', 'bananas', 'tofu', 'cats', 'bears', 21]
                                def pList(x):
                                    for i in range(len(x) - 2):
                                        print(str(x[i]) + ', ', end='')
                                    print(str(x[-2]) + ' and ' + str(x[-1]))
                                pList(spam)
                                

                                【讨论】:

                                  【解决方案22】:

                                  我没有深入研究所有答案,但我确实看到有人建议使用 join。我同意,但由于在学习加入之前这个问题没有出现在书中,所以我的答案是这样的。

                                  def To_String(my_list)
                                      try:
                                          for index, item in enumerate(my_list):
                                              if index == 0:                       # at first index
                                                  myStr = str(item) + ', '
                                              elif index < len(my_list) - 1:       # after first index
                                                  myStr += str(item) + ', '
                                              else:
                                                  myStr += 'and ' + str(item)      # at last index
                                          return myStr  
                                  
                                      except NameError:
                                          return 'Your list has no data!'
                                  
                                  spam = ['apples', 'bananas', 'tofu', 'cats']
                                  
                                  my_string = To_String(spam)
                                  
                                  print(my_string)
                                  

                                  结果:

                                  apples, bananas, tofu, and cats
                                  

                                  【讨论】:

                                    【解决方案23】:

                                    首先,我在做 python 和一般编码方面只有两个月的时间。

                                    这需要 2 小时以上才能解决,因为我将空列表变量设置为 lst = [],而不是使用 lst = "" ......尚不知道为什么。


                                            user_input = input().split()
                                            lst = "" # I had this as lst = [] but doesn't work I don't know why.... yet
                                            for chars in user_input:
                                                if chars == user_input[0]:
                                                    lst += user_input[0]
                                                elif chars  == user_input[-1]:
                                                    lst += ", and " + chars
                                                else:
                                                    lst += ", " + chars
                                        
                                             print(lst)
                                    
                                     
                                    

                                    编辑:更多细节

                                    .split() 函数会将我们的用户输入(字符串值)放入一个列表中。这给了我们索引,我们可以使用我们的 for 循环。 lst 空字符串变量仍在进行中的理解。接下来,在我们的 for 循环中查看每个索引,如果该索引与我们的布尔值匹配,我们将我们想要的内容添加到列表中。在这种情况下,nothing,以及 或最后只是另一个 ,强>(逗号)。然后打印。

                                    也就是说,大多数答案都包含 .join 方法,但在本书的这一部分中,没有谈到这一点。 这是第 6 章

                                    基本上就像我教你加减法然后给你一个分数测试。我们还没有准备好,只是混淆了,至少对我来说是这样。更不用说甚至没有人提供有关它的文档。 .join() 方法如果有人需要,可以在这里查看文档和示例的几个区域:

                                    #PayItForward

                                    【讨论】:

                                    • 你好。不太确定您希望如何在此处格式化,但目前有点令人困惑。您可以在此处查看格式化帮助:stackoverflow.com/editing-help
                                    • 谢谢。我保存了那个页面。出于某种原因,它一直将 URL 链接作为代码。因为它迫使我 CTRL-k 链接。但是将它们列在列表中会有所帮助。另外,我使好书更具可读性。再次感谢!
                                    • 更清楚了,谢谢!至于数组与字符串的关系,如果你想使用lst = [],它会将你的字符串 concat (+=) 分解成一个字符数组,你最终可能仍然不得不使用.join() 方法来输出。在您的情况下,离开lst = "" 可能会更好。真正熟悉文档总是好的建议。
                                    【解决方案24】:
                                    edgecase = []
                                    edgecase2 = ['apples','bananas']
                                    supplies = ['pens','staples','flamethrowers','binders']
                                    
                                    def list2string(list):
                                        string = ''
                                        for index, value in enumerate(list):
                                            if len(list) == 1:
                                                string = value
                                            elif index == len(list)-2:
                                                string += value + ' '
                                            elif index < len(list)-2:
                                                string += value + ',' + ' '
                                            else:
                                                string += 'and ' + value
                                        return string
                                    
                                    print(list2string(supplies))
                                    print(list2string(edgecase))
                                    print(list2string(edgecase2))
                                    

                                    输出

                                    : pens, staples, flamethrowers and binders
                                    : 
                                    : apples and bananas
                                    

                                    【讨论】:

                                      【解决方案25】:

                                      这就是我所做的,IMO 更直观...

                                      spam = ['apples','bananas','tofu','cats']
                                      
                                      def ipso(x):
                                          print("'" , end="")
                                          def run (x):
                                      
                                          for i in range(len(x)):
                                              print(x[i]+ "" , end=',')
                                      
                                      
                                          run(x)
                                          print("'")
                                      
                                      ipso(spam)
                                      

                                      【讨论】:

                                        【解决方案26】:

                                        为什么每个人都输入如此复杂的代码。

                                        请参阅下面的代码。即使对于初学者来说,它也是最简单和最容易理解的。

                                        import random
                                        
                                        def comma_code(subject):
                                        
                                             a = (len(list(subject)) - 1)
                                        
                                             for i in range(0, len(list(subject))):
                                        
                                                  if i != a:
                                                       print(str(subject[i]) + ', ', end="")
                                        
                                                  else:
                                                      print('and '+ str(subject[i]))            
                                        
                                        
                                        spam = ['apples','banana','tofu','cats']
                                        

                                        完成上述编码后,只需在 python shell 中输入 comma_code(spam) 即可。享受

                                        【讨论】:

                                          【解决方案27】:
                                          def commacode(mylist):
                                              mylist[-1] = 'and ' + mylist[-1]
                                              mystring = ', '.join(mylist)
                                              return mystring
                                          
                                          spam = ['apple', 'bananas', 'tofu', 'cats']
                                          
                                          print commacode(spam)
                                          

                                          【讨论】:

                                          • 使用spam = ['Cats'],您会得到“和猫”,因此您的解决方案无法满足要求...
                                          【解决方案28】:
                                          spam=['apples','bananas','tofu','cats']
                                          print("'",end="")
                                          def val(some_parameter):
                                          
                                          for i in range(0,len(spam)):
                                          if i!=(len(spam)-1):
                                          print(spam[i]+', ',end="")
                                          else:
                                          print('and '+spam[-1]+"'")
                                          val(spam)
                                          

                                          【讨论】:

                                          • 正确的pythonic方式已被接受为答案。这个答案实际上更像是使用 python 语法的“C”方式(使用带范围的 for 循环重新实现 str.join())。感谢您的努力,但这并没有以积极的方式解决这个问题。
                                          • 没问题。我是python的初学者,所以以前不知道join(),但现在我知道了一点。谢谢你的建议。
                                          【解决方案29】:

                                          这是我的解决方案。一旦我找到了 join 方法以及它是如何工作的,剩下的就跟着来了。

                                          spam = ['apples', 'bananas', 'tofu', 'cats']
                                          
                                          def commas(h):
                                              s = ', '
                                              print(s.join(spam[0:len(spam)-1]) + s + 'and ' + spam[len(spam)-1])
                                          
                                          commas(spam)
                                          

                                          【讨论】:

                                            【解决方案30】:
                                            spam=['apple', 'banana', 'tofu','cats']
                                            spam[-1]= 'and'+' '+ spam[-1]
                                            print (', '.join((spam)))
                                            

                                            【讨论】:

                                            • 您可能需要先复制您的列表以避免修改原始列表。
                                            猜你喜欢
                                            • 2017-09-13
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 2019-10-18
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 2020-08-30
                                            • 1970-01-01
                                            相关资源
                                            最近更新 更多