【问题标题】:Python3 - print a string from a list, seperated by commas with an 'and' before the last item in a listPython3 - 从列表中打印一个字符串,在列表中的最后一项之前用逗号分隔,并带有一个“和”
【发布时间】:2015-03-11 15:09:48
【问题描述】:

我正在寻找一种更简单(不一定是 Python 风格或更好)的方法来打印 Python3 中的项目列表,每个项目用逗号分隔,最后一个项目使用“和”。

目前为止

items=['foo','bar','baz']
print(','.join(items[0:-1]),'and',items[-1])

但是,我想将其用作 12-13 岁学生的资源的一部分,它并不是最易读的代码。

编辑:删除列表理解。

【问题讨论】:

    标签: python list printing


    【解决方案1】:

    你可以使用format方法:

     print("{} and {}".format(",".join(items[:-1]), items[-1]))
    

    第一个{} 将填充除最后一个元素之外的所有元素的join,然后您只需打印最后一个元素。

    【讨论】:

    • 好的,试试 items 一个项目
    • @JonClements 好点!这将需要围绕列表进行更多测试。 @MarcScott 我认为单独创建每个部分会更加明确和易于理解。 with_coma = ",".join(items[::-1]) 并在另一条线上组装整个 ouput = with_coma + " and " + items[:-1]
    • @MarcScott 谈到教育,这取决于编程的哪些方面/您想向他们展示的语言。
    • @JonClements @bvidal 已经使用条件来绕过长度为 0,1 或 2 的列表。我认为分开到单独的行肯定会有所帮助。不过,他们仍然会对join 感到困惑。话虽如此,我不想启动任何长度的for 循环,所以最好使用join
    • @MarcScott 我会使用for 循环而不是在join 中使用join - 与访问具有负索引的列表中的项目相比,通过列表可以轻松掌握.
    【解决方案2】:

    只需将其分解并发表评论 - 它可以是一种以更高级的方式进行的练习,例如:

    if not items:
        print('')
    elif len(items) == 1:
        print(items[0])
    elif len(items) == 2:
        print(' and '.join(items)) # or to show `print` options
        # print(*items, sep=' and ')
    else:
        words, last_word = items[:-1], items[-1]
        print(', '.join(words), 'and', last_word)
    

    使用Py3.x的扩展解包,可以使最后一个为:

    else:
        *words, last_word = items
        print(', '.join(words), 'and', last_word)
    

    或者,只需在批次上强制使用 ', '.join,然后在最后一个 ', ' 上拆分,然后根据您是否有分隔符,适当地打印。

    words, sep, last = ', '.join(items).rpartition(', ')
    if sep:
        print(words, 'and', last)
    else:
        print(last)
    

    【讨论】:

      【解决方案3】:

      这可能更容易阅读:

      items=['foo','bar','baz']
      
      for i, item in enumerate(items):
          if i == len(items) - 1:
              print('and ' + item)
          else:
              print(item + ',',end=' ')
      
      >>> foo, bar, and baz
      

      为 Python3 更新,我也想出了这个(非常相似):

      items=['foo', 'tri', 'baz']
      
      s = ''
      for i, item in enumerate(items):
          if i == len(items) - 1:
              s += 'and {}'
          else:
              s += '{}, '
      
      print(s.format(*items))
      

      【讨论】:

      • 我喜欢这个外观。他们还没有报道enumerate,但我当然可以介绍它。最后一个 print 上的偷偷摸摸的逗号可能会抛出一些,但它比组装一个完整的字符串要好。
      • 对于少于 3 个元素的列表,这里还有一个很好的 bug 需要修复。
      • 最后一行必须在 python 3 中通过反射读取print(item + ',',end=' ')。
      • @MarcScott 更新了...对此感到抱歉!
      【解决方案4】:

      假设您的列表至少包含 2 个字符串:

      print(','.join(items[:-1]) + ' and ' + items[-1])

      我认为对于那个年龄来说已经足够清楚了

      【讨论】:

        猜你喜欢
        • 2017-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-16
        • 2011-06-10
        • 2015-12-30
        • 1970-01-01
        相关资源
        最近更新 更多