[英]Python printing lists with tabulate
我正在嘗試打印天文學模擬的輸出,以便在控制台中看起來不錯。 我生成了4個numpy數組,分別稱為Amplitude,Mass,Period和Eccentricity,我想將它們放在一個表中。 每個數組的第一個索引是行星1的值,第二個索引是行星2的值,依此類推。
所以我的數組看起來像(值都是浮點數,例如'a1'只是一個占位符):
amp = [a1 a2 a3 a4]
mass = [m1 m2 m3 m4]
period = [p1 p2 p3 p4]
ecc = [e1 e2 e3 e4]
我希望桌子看起來像:
planet|amp|mass|period|ecc
1 |a1 |m1 |p1 |e1
2 |a2 |m2 |p2 |e2
...
我試過使用制表和類似的東西:
print tabulate(['1', amp[0], mass[0], period[0], ecc[0]], headers=[...])
但是我得到一個錯誤的'numpy.float64'對象是不可迭代的
任何幫助,將不勝感激!
像這樣使用zip()
:
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)
代替使用planet = [1, 2, 3, 4]
,可以使用如下的enumerate()
:
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
tabulate.tabulate()將列表(或數組)列表作為其主要參數,您已為其指定了一個浮點列表(以及一個“ 1”)。
因此,您想一次放入所有數據。
您需要創建新列表,其中每個列表都是新表的一個水平行。 您還需要在前面添加行號。
首先構建新的列表/數組,其中:
list1=[1,a1,m1,p1,e1]
list2=[2,a2,m2,p2,e2]
...
然后嘗試:
print tabulate([list1, list2, list3, list4], headers=[...])
您可以將zip()的用法與制表結合起來,以創建外觀更好的表:
from tabulate import tabulate
headers = ['planet', 'amp', 'mass', 'period', 'ecc']
amp = [1.1, 1.2, 1.3, 1.4]
mass = [2.1, 2.2, 2.3, 2.4]
period = [3.1, 3.2, 3.3, 3.4]
ecc = [4.1, 4.2, 4.3, 4.4]
planet = range(1, len(amp)+1)
table = zip(planet, amp, mass, period, ecc)
print(tabulate(table, headers=headers, floatfmt=".4f"))
planet amp mass period ecc
-------- ------ ------ -------- ------
1 1.1000 2.1000 3.1000 4.1000
2 1.2000 2.2000 3.2000 4.2000
3 1.3000 2.3000 3.3000 4.3000
4 1.4000 2.4000 3.4000 4.4000
您可以使用\\t
。
例如:
print 'a\t','b\t','\n','c\t','d\t'
輸出:
a b
c d
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.