简体   繁体   English

如何遍历二维列表以打印表格?

[英]How to iterate a 2d list to print a table?

I have a class like this: 我有这样的课:

class example:
    def get_a(self): return [1,2,3]
    def get_b(self): return [4,5,6]
    def get_c(self): return [7,8,9]
    def get_all(self): return [['a',self.get_a()],['b',self.get_b()],['c',self.get_c()]]

And now I would like to use the return value of get_all to print a table like this: 现在,我想使用get_all的返回值来打印这样的表:

a b c
1 4 7
2 5 8
3 6 9

I know I can get the same output via: 我知道我可以通过以下方式获得相同的输出:

def example_print():
    x = example()
    print 'a b c'
    for a,b,c in zip(x.get_a(),x.get_b(),x.get_c()):
         print a,b,c 

But I am clueless on how to iterate the 2d list returned by get_all to print the same, especially as I am looking for a way that does not have the number of items hardcoded (want to use same way of printing the list for different instances that may have more "columns"). 但是我对如何迭代get_all返回的2d列表以打印相同内容get_all ,特别是因为我正在寻找一种不对项目进行硬编码的方式(想对不同的实例使用相同的方式打印列表)可能会有更多的“列”)。

A simple way would be to use the zip transpose idiom, something like: 一种简单的方法是使用zip转置习惯,例如:

for x in zip(*e.get_all()):
    print(*x)

In Python 2, make sure you use: 在Python 2中,请确保使用:

from __future__ import print_function 

Or better yet, just switch to Python 3. 或者更好的是,只需切换到Python 3。

If your list actually has two levels of nesting. 如果您的列表实际上有两个嵌套级别。 Which would require your method to be something like: 这将需要您的方法是这样的:

return  [['a',*self.get_a()],['b',*self.get_b()],['c',*self.get_c()]]

Or something equivalent in Python 2... 或等同于Python 2的东西...

If you change your get_all definition to this: 如果将get_all定义更改为此:

def get_all(self): return ['a'] + self.get_a(), ['b'] + self.get_b(), ['c'] + self.get_c()

Then you'll be able to use something like this: 然后,您将可以使用以下内容:

from __future__ import print_function

x = example()
for line in zip(*x.get_all()):
     print(*line)

I tried out this and it works. 我尝试了一下,它起作用了。

class example:
    def get_a(self): return [1,2,3]
    def get_b(self): return [4,5,6]
    def get_c(self): return [7,8,9]


    def get_all(self):
        a = [['a', *self.get_a()], ['b', *self.get_b()], ['c', *self.get_c()]]
        r = []
        for line in zip(*a):
            r.append([*line])
        return r

if __name__ == '__main__':
    E = example()
    v = E.get_all()
    for i in v:
        print(*i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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