带有列表的Python打印列表 [英] Python printing lists with tabulate

查看:80
本文介绍了带有列表的Python打印列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印天文学模拟的输出,以便它在我的控制台中看起来不错.我生成了4个numpy数组,分别称为Amplitude,Mass,Period和Eccentricity,我想将它们放在一个表中.每个数组的第一个索引是行星1的值,第二个索引是行星2的值,等等.

I'm trying to print the output of an astronomy simulation so that it looks nice in my console. I generate 4 numpy arrays called Amplitude, Mass, Period and Eccentricity and I want to put them in a table. The first index of each array are the values for planet 1, the second for planet 2 etc.

所以我的数组看起来像(值都是浮点数,例如'a1'只是一个占位符):

So my arrays look like (values are all float numbers, eg 'a1' just a placeholder):

amp = [a1 a2 a3 a4]
mass = [m1 m2 m3 m4]
period = [p1 p2 p3 p4]
ecc = [e1 e2 e3 e4]

我希望我的桌子看起来像这样:

I'd like my table to look like:

planet|amp|mass|period|ecc
1     |a1 |m1  |p1    |e1
2     |a2 |m2  |p2    |e2
...

我尝试使用制表法之类的方法:

I've tried using tabulate and something like:

print tabulate(['1', amp[0], mass[0], period[0], ecc[0]], headers=[...])

但是我得到一个'numpy.float64'对象不可迭代的错误

but I get an error of 'numpy.float64' object is not iterable

任何帮助将不胜感激!

推荐答案

使用 zip() 像这样:

Use zip() like this:

amp = ['a1', 'a2', 'a3', 'a4']
mass = ['m1', 'm2', 'm3', 'm4']
period = ['p1', 'p2', 'p3', 'p4']
ecc = ['e1', 'e2', 'e3', 'e4']
planet = [1, 2, 3, 4]


titles = ['planet', 'amp', 'mass', 'period', 'ecc']

print '{:<6}|{:<6}|{:<6}|{:<6}|{:<6}'.format(*titles)
for item in zip(planet, amp, mass, period, ecc):
    print '{:<6}|{:<6}|{:<6}|{:<6}|{:<6}'.format(*item)

您可以使用

Instead of using planet = [1, 2, 3, 4], you can use enumerate() like below:

print '{:<6}|{:<6}|{:<6}|{:<6}|{:<6}'.format(*titles)
for i, item in enumerate(zip(amp, mass, period, ecc)):
    print '{:<6}|{:<6}|{:<6}|{:<6}|{:<6}'.format(i+1, *item)

输出:

>>> python print_table.py
planet|amp   |mass  |period|ecc
1     |a1    |m1    |p1    |e1
2     |a2    |m2    |p2    |e2
3     |a3    |m3    |p3    |e3
4     |a4    |m4    |p4    |e4

这篇关于带有列表的Python打印列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆