簡體   English   中英

輸出具有不同列數並在 Python 中換行的格式化二維文本

[英]Output formatted 2D text with different number of columns and wrapping in Python

我需要打印一個二維數組,例如

a = [[100.0, 200.0, 300.0, 400.0, 500.0, 600.0],
     [700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0],
     [1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0]]

到具有以下格式的文本文件:

row=    1   1.00E+02    2.00E+02    3.00E+02    4.00E+02    5.00E+02
            6.00E+02    
row=    2   7.00E+02    8.00E+02    9.00E+02    1.00E+03    1.10E+03
            1.20E+03        
row=    3   1.30E+03    1.40E+03    1.50E+03    1.60E+03    1.70E+03
            1.80E+03    

現在,如果它是一個簡單的表格,已經有很多好的帖子和解決方案,例如使用print('{0:<8} {1:<8} {2:<8} {3:<8} {4:<8}'.format(...)或循環遍歷i行和print(*i.split(","), sep = "\n")等。但是數組中的元素必須是包裝在 5 列中(例如,如果數組是 4 x 14,則每行的數字跨越三行但不是一直),而且某些列缺少前兩列的事實讓我很難。我寧願不使用任何花哨的庫,但是像 Numpy 和 Pandas 這樣的普通庫非常好。列的寬度可以是靈活的,我已經看到以下文件也可以接受,主要限制是 5 列換行:

 row=    1   1.50768831520556500E+03   1.61593623564084623E+03   1.72793908252278788E+03   1.84745178229805083E+03   1.89005237234217384E+03
             1.93242770965689124E+03   1.94285107599349976E+03   1.95428167992566091E+03   1.97250548659241736E+03   2.00154699718308871E+03
             2.03838485708810049E+03   2.07823624774815426E+03   2.13405634328665110E+03   1.95456774471011431E+03
 row=    2   1.44364188653061069E+03   1.52792163517318954E+03   1.61391596698350054E+03   1.70333946512927673E+03   1.73425508334279334E+03
             1.76507211642371681E+03   1.77245044015945177E+03   1.78083908332863643E+03   1.79497739305904815E+03   1.81799782545806261E+03
             1.84660527255144098E+03   1.87589773534454025E+03   1.93023915683827636E+03   1.91021293716667878E+03

您可以使用列表推導將a每一row拆分為<= 5的部分,並使用{:.2E}格式化所有數字以獲得科學記數法。

這也被 4 個空格隔開

with open('output.txt', 'w') as w:
    for i, row in enumerate(a, start=1):
        # Write start
        w.write(f'row=    {i}    ')
        # Get spaces for row overflow
        space = (12 + len(str(i)))*' '
        # Split row into sections of 5
        tempa = [row[i:i+5] for i in range(0, len(row), 5)]
        # Write row and .join sections by newline + spaces
        w.write(
            f'\n{space}'.join(['    '.join([f'{a:.2E}' for a in b]) for b in tempa]))
        w.write('\n')
row=    1    1.00E+02    2.00E+02    3.00E+02    4.00E+02    5.00E+02
             6.00E+02
row=    2    7.00E+02    8.00E+02    9.00E+02    1.00E+03    1.10E+03
             1.20E+03
row=    3    1.30E+03    1.40E+03    1.50E+03    1.60E+03    1.70E+03
             1.80E+03

以科學計數法顯示小數

如何將列表分成n等份,python

如有必要,請隨意簡單地添加和刪除字符串中的間距

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM