gpt4 book ai didi

python - 如何迭代二维列表来打印表格?

转载 作者:行者123 更新时间:2023-11-28 21:37:13 25 4
gpt4 key购买 nike

我有一堂这样的课:

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

现在我想使用 get_all 的返回值来打印这样的表格:

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

我知道我可以通过以下方式获得相同的输出:

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

但是我对如何迭代 get_all 返回的二维列表以打印相同的内容一无所知,特别是当我正在寻找一种没有硬编码的项目数量的方法时(想要使用为可能有更多“列”的不同实例打印列表的方式相同)。

最佳答案

一个简单的方法是使用 zip 转置惯用法,例如:

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

在 Python 2 中,请确保使用:

from __future__ import print_function 

或者更好的是,切换到 Python 3。

如果您的列表实际上有两层嵌套。这需要您的方法类似于:

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

或 Python 2 中的等效内容...

关于python - 如何迭代二维列表来打印表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com