【问题标题】:How to print a list with specified column width in Python?如何在 Python 中打印具有指定列宽的列表?
【发布时间】:2017-10-30 14:37:41
【问题描述】:

我有一个类似的列表

mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

如何打印指定列宽的列表

比如我想打印column = 5然后换行

print(mylist, column= 5)
[ 1,  2,  3,  4,  5, 
  6,  7,  8,  9, 10, 
 11, 12, 13, 14, 15, 
 16, 17, 18, 19, 20]

或者我想打印column = 10 然后换行

print(mylist, column= 10)
[ 1,  2,  3,  4,  5, 6,  7,  8,  9, 10, 
 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

我知道我可以使用 for-loop 来做到这一点,但我想知道是否有一个函数可以做到这一点?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用 numpy 数组而不是列表并重塑您的数组。

    >>> import numpy as np
    >>> array = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
    >>>
    >>> column = 5
    >>> print(array.reshape(len(array)/column, column))
    [[ 1  2  3  4  5]
     [ 6  7  8  9 10]
     [11 12 13 14 15]
     [16 17 18 19 20]]
    >>>>>> column = 10
    >>> print(array.reshape(len(array)/column, column))
    [[ 1  2  3  4  5  6  7  8  9 10]
     [11 12 13 14 15 16 17 18 19 20]]
    

    当然,如果无法将array 划分为column 大小相等的列,这将抛出ValueError

    【讨论】:

      【解决方案2】:

      不知道为什么,但我认为可以通过将行数固定为 -1 来使用 numpy array reshape 来完成我认为你想要实现的目标

      import numpy as np
      array=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) array
      array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
             18, 19, 20])
      array.reshape(-1,5)
      

      给予

      array([[ 1,  2,  3,  4,  5],
             [ 6,  7,  8,  9, 10],
             [11, 12, 13, 14, 15],
             [16, 17, 18, 19, 20]])
      
      array.reshape(-1,10)
      

      给予

      array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
             [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]])
      

      【讨论】:

      【解决方案3】:

      您也可以使用切片来做到这一点。

      mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
      
      def print_list(mylist, no_of_cols):
          start_index = 0
          for i in range(no_of_cols, len(mylist), no_of_cols):
              print mylist[start_index:i]
              start_index = i
      
          if len(mylist) > start_index:
              print mylist[start_index:len(mylist)]
      
      print_list(mylist, 5)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-14
        • 2019-02-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多