首页 > 解决方案 > 我试图将三个不同大小的数组打印到表格中

问题描述

a = [1, 2, 3]    
b = [a, b, c, d]    
c = ["why", "cant", "i", "make", "this", "work"]

期望的输出:

a     b     c  
1     a     why  
2     b     cant  
3     c     I  
      d     make  
            this  
            work  

标签: pythonpython-3.x

解决方案


你可以参考这段代码。

a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ["why", "cant", "i", "make", "this", "work"]

def get_safenode(l, i):
    if i<len(l):
        an=l[i]
    else:
        an=''
    return str(an)

maxlen = max(len(a), len(b), len(c))
print('%3s %3s %-5s' % ('a','b','c'))
for i in range(maxlen):
    an = get_safenode(a, i)
    bn = get_safenode(b, i)
    cn = get_safenode(c, i)
    print('%3s %3s %-5s'%(an, bn, cn))

输出是这样的。

  a   b c    
  1   a why  
  2   b cant 
  3   c i    
      d make 
        this 
        work 

推荐阅读