【问题标题】:Turn the Python 2D matrix/list into a table将 Python 2D 矩阵/列表转换为表格
【发布时间】:2014-03-26 18:34:26
【问题描述】:

我该如何转这个:

students = [("Abe", 200), ("Lindsay", 180), ("Rachel" , 215)]

进入这个:

Abe     200
Lindsay 180
Rachel  215

编辑:这应该适用于任何大小的列表。

【问题讨论】:

    标签: python list matrix 2d tuples


    【解决方案1】:

    使用string formatting:

    >>> students = [("Abe", 200), ("Lindsay", 180), ("Rachel" , 215)]
    >>> for a, b in students:
    ...     print '{:<7s} {}'.format(a, b)
    ...
    Abe     200
    Lindsay 180
    Rachel  215
    

    【讨论】:

      【解决方案2】:

      使用 rjust 和 ljust:

      for s in students:
          print s[0].ljust(8)+(str(s[1])).ljust(3)
      

      输出:

       Abe     200
       Lindsay 180
       Rachel  215
      

      【讨论】:

        【解决方案3】:

        编辑:有人更改了问题的关键细节 Aशwini चhaudhary 给出了一个很好的答案。如果您现在还不能学习/使用 string.format,那么解决问题的更通用/算法方法如下:

        for (name, score) in students:
            print '%s%s%s\n'%(name,' '*(10-len(name)),score)
        

        【讨论】:

          【解决方案4】:

          对于 Python 3.6+,您可以使用 f-string 作为 Ashwini Chaudhary 回答的 单行 版本:

          >>> students = (("Abe", 200), ("Lindsay", 180), ("Rachel" , 215))
          >>> print('\n'.join((f'{a:<7s} {b}' for a, b in students)))
          Abe     200
          Lindsay 180
          Rachel  215
          

          如果您不知道列表中最长字符串的长度,您可以计算如下:

          >>> students = (("Abe", 200), ("Lindsay", 180), ("Rachel" , 215))
          >>> width = max((len(s[0]) for s in students))
          >>> print('\n'.join((f'{a:<{width}} {b}' for a, b in students)))
          Abe     200
          Lindsay 180
          Rachel  215
          

          【讨论】:

            猜你喜欢
            • 2018-12-11
            • 1970-01-01
            • 2019-04-23
            • 1970-01-01
            • 1970-01-01
            • 2017-07-07
            • 2020-09-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多