[英]How to make a list of lists display vertically
So I have a list L. 所以我有一个清单L。
L = [[1],[2,3],[3,4,5]]
How would I go about to make it look like this. 我将如何使它看起来像这样。
1 2 3
3 4
5
I want this to be able to iterate. 我希望这能够迭代。 I think the best way would be nested for loops, but I am confused on where to begin.
我认为最好的方法是嵌套循环,但是我对从哪里开始感到困惑。
EDIT*** 编辑***
I managed to make something that resembles what I want to do. 我设法做出了与我想做的事情相似的事情。
L = [[1],[2,3],[3,4,5],[]]
max_list= []
maxlen=max(len(l) for l in L)
for row in range(maxlen):
max_list.append([])
for col in tab:
try:
max_list[row].append(col[row])
except:
max_list[row].append('')
for col in max_list:
print(col)
Output: 输出:
[1, 2, 3, '']
['', 3, 4, '']
['', '', 5, '']
As of right now how would I format it to 截至目前,我如何将其格式化为
1 2 3
3 4
5
Solutions are not so elegant, too much code... 解决方案不是那么优雅,代码太多...
L = [[1],[2,3],[3,4,5]]
max_length = max(map(len, L)) # finding max length
output = zip(*map(lambda x: x + [' '] * (max_length - len(x)), L)) # filling every sublist with ' ' to max_length and then zipping it
for i in output: print(*i) # printing whole result
Output: 输出:
1 2 3
3 4
5
So 3rd line is not that obvious, i will break it down 所以第三行不是那么明显,我将其分解
>>> list(map(lambda x: x + [' '] * (max_length - len(x)), L))
[[1, ' ', ' '], [2, 3, ' '], [3, 4, 5]]
>>> list(zip(*map(lambda x: x + [' '] * (max_length - len(x)), L)))
[(1, 2, 3), (' ', 3, 4), (' ', ' ', 5)]
UPDATE 更新
To lengthen the spaces you need to provide keyword argument sep
to print
function: for i in output: print(*i, sep= ' ')
要加长空格,您需要为
print
功能提供关键字参数sep
: for i in output: print(*i, sep= ' ')
assuming you are just trying to print it in that format, how about this code: 假设您只是尝试以该格式打印,那么这段代码如何:
L = [[1],[2,3],[3,4,5]]
#1 2 3
# 3 4
# 5
for i in range(len(L)):
for lst in L:
if (i == 0):
print (lst[0], end='')
if (i == 1 and len(lst)>1):
print (lst[1], end='')
if (i == 2 and len(lst)>2):
print (lst[2], end='')
print ('\n')
it only works for this specific case, where L = [[1],[2,3],[3,4,5]]
but it prints the desired output. 它仅适用于此特定情况,其中
L = [[1],[2,3],[3,4,5]]
但它会打印所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.