找到你要的答案

Q:How do you make a table out of multiple list in list?

Q:如何在列表中列出多个列表?

How do I make table if we have multiple list and that list has within list?

For example if we have

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

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

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

Please notice each list has same number of list within it however inside list has different number of items. The result I am looking for looks like this

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

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

例如,如果我们有

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

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

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

Please notice each list has same number of list within it however inside list has different number of items. The result I am looking for looks like this

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

This should do what you want..

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)))

Then you just call it.

>>> 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

这应该做你想要的..

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
answer2: 回答2:
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)]
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)]
python  python-3.x