我有一个带有列表的列表,我想在要导入的任何其他模块(即pprint
)的列[[w / o中打印它。任务仅对我而言是了解列表的迭代。这是我的列表列表:
tableData = [['a', 'b', 'c', 'd'],
['1', '2', '3', '4'],
['one', 'two', 'three', 'four']]
而且我希望它看起来像这样:
a 1 one b 2 two c 3 three d 4 four
我设法对它的第一行进行了一些硬编码,但是我不知道如何对迭代进行建模。参见:
def printTable(table): print(table[0][0].rjust(4," ") + table[1][0].rjust(4," ") + table[2][0].rjust(4," "))
>>> for v in zip(*tableData):
print (*v)
a 1 one
b 2 two
c 3 three
d 4 four
来转置表格,然后使用zip
来输出行:zip
如果您有一个列表,例如my_list = [('Math',80),('Physics',90),('Biology',50)],那么我们可以说这是3X2矩阵。它的转置将是2X3矩阵。
row_format = '{:<4}' * len(tableData)
for t in zip(*tableData):
print(row_format.format(*t))
将进行以下输出
[('Math','Physics','Biology'),(80,90,50)]] >>