【问题标题】:automate the boring stuff comma code自动化无聊的东西逗号代码
【发布时间】:2017-09-13 14:20:17
【问题描述】:
spam = ['apples', 'bananas', 'tofu', 'cats']

def stringmaker(data):
    tempdata = 0
    datastring = ''
    stringlist = []
    stringdata = ''
    stringdata += ', '.join(data)
    stringlist += stringdata.split()
    tempdata = stringlist
    tempdata = str(stringlist.insert(-1, 'and'))
    datastring += ' '.join(stringlist)
    print(datastring)


stringmaker(spam)

在 Automate the Boring Stuff with Python page 102 中,练习项目 Comma Code - Comma Code

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

我编写的代码在本章的上下文中运行并保持不变。我在这个网站和谷歌上查看了其他答案,我很惊讶我的代码有多么不同而且可能很愚蠢。有人可以帮我指出我的代码的所有缺点吗?

我真的希望它尽可能像 Python 和尽可能少的行。

【问题讨论】:

  • 如果这是您认为可以改进的工作代码,请参阅Code Review。但请注意,“as pythonic and as few lines” 有时会发生冲突。
  • data[0] if len(data) == 1 else ', and '.join([', '.join(data[:-1]), data[-1]]) 我会这样做

标签: python string list python-3.x function


【解决方案1】:
def stringmaker(data):
    return ", ".join(data[:-1]) + " and " + data[-1]

它的作用:用“,”加入列表但最后一个元素,然后添加“和”以及最后一个元素

正如您问题中的评论所说,有时最好放弃“单行”以使您的代码更具可读性。

另外请注意,如果 data 为空列表,则此代码目前不起作用

【讨论】:

  • 我会删除您的第一个示例,因为第二个示例更短且更具可读性。此外,您的函数没有 return 语句。
  • 什么是table?你的意思是data
  • 我听从了你的两个建议
  • @WNG ... + ", and " + ... 如果您想遵循规范 - 它包括牛津逗号。
【解决方案2】:

你可以使用类似的东西:

words = ['apples', 'bananas', 'tofu', 'cats']
def spam(words):
   if words: # prevents parsing an empty list
        return ", ".join(words[:-1]) + ", and " + words[-1]
print spam(words)
# apples, bananas, tofu, and cats

Demo


注意: 在英语中,您通常不会在and 之前使用commas

【讨论】:

  • 我不同意“你通常不使用”serial comma
  • 对此存在一些争议,例如美联社在协调连词之前不使用逗号。无论如何...谢谢你指出!我的母语是葡萄牙语,我们不在 e(和)之前使用 virgulas(逗号);)
【解决方案3】:

它会做你的工作:

spam = ['apples', 'bananas', 'tofu', 'cats',]
def commacode(spam):
    return print(', '.join(spam[:-1]) + ' and ' + spam[-1])

commacode(spam)

【讨论】:

    【解决方案4】:

    我认为这给出了最好的输出。(ps:我也是初学者)。

    def ltos(list):
        empty_string = ''
        for i in list[:-2]:
            empty_string += i + ", "
        empty_string += list[-2]
        empty_string += ' and ' + list[-1] + '.'
        print(empty_string)
    
    myex = ['dumb', 'retard', 'awkward', 'brainless', 'immature', 'ignored', 'invisible']
    ltos(myex)
    

    输出:愚蠢、迟钝、笨拙、无脑、不成熟、被忽视和隐形。

    【讨论】:

      【解决方案5】:

      我做了这个练习,但将用户输入视为一个列表:(lista == list but in spanish :3)

       import sys
      lista = []
      
      while True:
          print('enter the '+ str(len(lista) + 1) +' item in your list ' "(or enter nothing to stop)")
          item = input()
          if item == '':
              break
          lista = lista + [item]
      lista[-1] = 'and ' + lista[-1]
      print('your complete list is: \n' + (", ".join(lista)))
      sys.exit()
      

      【讨论】:

      • 欢迎来到stackoverflow!您能否更详细地解释一下您想要实现的目标,并添加一些关于所使用的技术/语言的标签?
      • 我试着让这个程序尽可能灵活,每次都制作自定义列表,我使用 python 3.x。我是新手>。
      【解决方案6】:

      这是我的解决方案,和你一样,我努力了三天来部分解决这个问题。 但这真的很棒。

      这是代码:

      spam = ['apples', 'bananas', 'tofu', 'cats']
      def list_string(the_list):
       number_list = len(the_list)
       if number_list == 1:
           print(the_list[0])
       elif number_list == 2:
           print(the_list[0] + ' and ' + the_list[1])
       elif number_list > 2:
           for a in range(1):
               print(', '.join(the_list[0 :len(the_list) - 1]) + ', and ' + the_list[len(the_list) - 1])
      
      
      
      list_string(spam)
      

      【讨论】:

        【解决方案7】:

        我明白了

        list = []
        for i in range(3):
            value = str(input())
            list.append(value)
        list.insert(2, 'and')
        print(list)
        

        这样,唯一需要根据您想要列表的时间长度进行更改的是代码的 range(3) 和 .insert(2, 'and') 部分。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-18
          • 2020-05-14
          • 2018-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多