Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中打印具有指定列宽的列表?_Python - Fatal编程技术网

如何在Python中打印具有指定列宽的列表?

如何在Python中打印具有指定列宽的列表?,python,Python,我有一张这样的清单 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] print(mylist, column= 10) [ 1

我有一张这样的清单

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]
print(mylist, column= 10)
[ 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= 5)
[ 1,  2,  3,  4,  5, 
  6,  7,  8,  9, 10, 
 11, 12, 13, 14, 15, 
 16, 17, 18, 19, 20]
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来实现这一点,但我想知道是否已经有了这样做的函数?

使用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]]

当然,如果无法将
数组
划分为大小相同的
这将抛出一个
ValueError

不确定原因,但我认为可以通过将行数固定为-1,使用numpy array REFORMATE来实现我认为您想要实现的目标

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)
给予


您也可以通过使用切片来实现这一点

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)

酷,我不知道
重塑
接受-1作为参数。更多信息请点击此处: