如何从列表中的多个列表中创建一个表?

时间:2015-10-07 19:19:57

标签: python python-3.x

如果我们有多个列表并且该列表在列表中,我如何创建表?

例如,如果我们有

List1= [['apple','ball','cat'],['rat','hat','mat']]

List2=[[1,4,5,6],[2,'rat',5,6]]

List3 = [[23,34,54],[12,23]]

请注意每个列表中的列表具有相同的列表,但是列表中的列表具有不同的项目数。 我正在寻找的结果看起来像这样

List1    List2   List3
apple    1        23
ball     4        34
cat      5        54
rat      6        12 
hat      2        23
mat      rat
         5
         6

2 个答案:

答案 0 :(得分:1)

List1 = [['apple', 'ball', 'cat'], ['rat', 'hat', 'mat']]
List2 = [[1, 4, 5, 6], [2, 'rat', 5, 6]]
List3 = [[23, 34, 54], [12, 23]]


for x, y, z in zip(List1, List2, List3):
  for a, b, c in zip(x, y, z):
    print a, b, c

apple 1 23
ball 4 34
cat 5 54
rat 2 12
hat rat 23


print [(a, b, c) for x, y, z in zip(List1, List2, List3) for a, b, c in zip(x, y, z)]

[('apple', 1, 23), ('ball', 4, 34), ('cat', 5, 54), ('rat', 2, 12), ('hat', 'rat', 23)]

答案 1 :(得分:1)

这应该做你想要的......

from itertools import chain, zip_longest
def lister(l1, l2, l3):
    print('List1   List2   List3')
    for a,b,c in zip_longest(chain(*l1), chain(*l2), chain(*l3), fillvalue=''):
       print('{:7s} {:7s} {:7s}'.format(str(a),str(b),str(c)))

然后你就叫它。

>>> lister(List1, List2, List3)

List1   List2   List3
apple   1       23
ball    4       34
cat     5       54
rat     6       12
hat     2       23
mat     rat
        5
        6