Python 将n个列表压缩在一起

Python 将n个列表压缩在一起,python,list,Python,List,我试图以垂直排序的列显示列表,列数由用户决定。我想使用zip(),但我似乎不知道如何告诉它通过nno列表 #!/usr/bin/env python import random lst = random.sample(range(100), 30) lst = sorted(lst) col_size = int(raw_input('How many columns do you want?: ')) sorting = 'Vertical' if sorting == 'Vertic

我试图以垂直排序的列显示列表,列数由用户决定。我想使用
zip()
,但我似乎不知道如何告诉它通过
n
no列表

#!/usr/bin/env python

import random

lst = random.sample(range(100), 30)
lst = sorted(lst)

col_size = int(raw_input('How many columns do you want?: '))
sorting = 'Vertical'

if sorting == 'Vertical':
    # vertically sorted
    columns = []
    n = len(lst)//col_size

    for i in range(0, len(lst), n):
        columns.append(lst[i:i+n])

    print '\nVertically Sorted:'

    print columns
    print zip(*columns)
这就产生了这样的结果:

How many columns do you want?: 4

Vertically Sorted:
[[0, 2, 4, 11, 12, 16, 23], [24, 31, 32, 36, 41, 48, 50], [52, 54, 61, 62, 63, 64, 67], [76, 80, 81, 89, 91, 92, 94], [96, 97]]
[(0, 24, 52, 76, 96), (2, 31, 54, 80, 97)]
如果我知道列数(例如4),我可以编码:

for c1, c2, c3, c4 in zip(columns[0], columns[1], columns[2], columns[3]):
    print str(c1), str(c2).rjust(8), str(c3).rjust(8), str(c4).rjust(8)

但既然我没有,我该如何使用
zip
?如您所见,我尝试了
zip(*columns)
,但由于上一个列表中的项目数量不相等,因此失败了。

zip无法完成您所需的操作,因为行大小不同。当行不均匀时,Map将进行转置

请参阅下面的代码帮助

节目 随机输入

lst=随机样本(范围(100),30) lst=已排序(lst)

col_size=int(原始输入('需要多少列?:')) 排序='垂直'

如果排序==“垂直”: #垂直排序 列=[] n=len(lst)//列大小

for i in range(0, len(lst), n):
    columns.append(lst[i:i+n])

print '\nColumns:'
columns = map(None,*columns)
print columns
print '\nVertically Sorted:'

col_width = max(len(str(word)) for row in columns for word in row) + 2  # padding
for row in columns:
  print "".join(str(word).ljust(col_width) for word in row if word is not None)
输出
Zip不符合您的要求,因为行大小不同。当行不均匀时,Map将进行转置

请参阅下面的代码帮助

节目 随机输入

lst=随机样本(范围(100),30) lst=已排序(lst)

col_size=int(原始输入('需要多少列?:')) 排序='垂直'

如果排序==“垂直”: #垂直排序 列=[] n=len(lst)//列大小

for i in range(0, len(lst), n):
    columns.append(lst[i:i+n])

print '\nColumns:'
columns = map(None,*columns)
print columns
print '\nVertically Sorted:'

col_width = max(len(str(word)) for row in columns for word in row) + 2  # padding
for row in columns:
  print "".join(str(word).ljust(col_width) for word in row if word is not None)
输出 使用
IT.izip_longest(*[iterable]*n)
lst
中的项目按大小分组
n
。(有关石斑鱼配方的详细说明,请参阅。)

屈服

   0   7  14  21  28
   1   8  15  22  29
   2   9  16  23    
   3  10  17  24    
   4  11  18  25    
   5  12  19  26    
   6  13  20  27    
使用
IT.izip_longest(*[iterable]*n)
lst
中的项目按大小分组
n
。(有关石斑鱼配方的详细说明,请参阅。)

屈服

   0   7  14  21  28
   1   8  15  22  29
   2   9  16  23    
   3  10  17  24    
   4  11  18  25    
   5  12  19  26    
   6  13  20  27    

从结果中删除无元素后,扩展最后一个无元素列表以获得相等长度zip。

在从结果中删除无元素后,扩展最后一个无元素列表以获得相等长度zip。

在此ans中,列表是水平排序的。我想垂直排序。在这个ans中,列表是水平排序的。我想垂直排序。