简体   繁体   中英

How to vertically print 2d list with different lengths in python

In fact this I try to do.

I have a class call card

class Card(object):
def __init__(self, value, folldown,canMove):
    self.value = value
    self.folldown = folldown
    self.canMove=canMove

And I use this to print

for i in range(len(cards)):
  for j in range(len(cards[i])):
       print cards[i][j].value

I want to print a 2d list with different sizes a=[[0, 1], [0, 1, 2], [0, 1, 2, 3]]

an I want to print like this

0 0 0
1 1 1
  2 2
    3

I was trying to print like this

for i in range(len(a)):
  for j in range(len(a[i])):
       print a[i][j]

but the result was

0
1
0
1
2
0
1 
2 
3 
a = [[0, 1], [0, 1, 2], [0, 1, 2, 3]]
print '\n'.join(['\t'.join([str(x[i]) if len(x) > i else '' for x in a]) for i in range(len(max(a)))])

#0    0    0
#1    1    1
#     2    2
#          3

Another, one line solution

a = [[0, 1], [0, 1, 2], [0, 1, 2, 3]]
from itertools import izip_longest
print "\n".join(("\t".join(map(str,l)) for l in izip_longest(*a, fillvalue="")))

you get:

0   0   0
1   1   1
    2   2
        3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM