簡體   English   中英

Python:在不使用非標准庫的情況下將字符串 output 格式化為表格的靈活方法

[英]Python: Flexible way to format string output into a table without using a non-standard library

有沒有辦法在不使用任何非標准 Python 庫的情況下將字符串 output 格式化為具有靈活列寬的表

(例如,在下面的代碼中,第一列中最長的條目是 'United States',它有 13 個字符,因此表格列寬可能只有 13[+2] 個字符,而不是 20 個字符的固定寬度)。

這個問題的答案有很多很好的建議,但它們依賴於非標准庫(熊貓、制表等)。

使用字符串格式規范迷你語言的示例代碼:

countries_dict = {'Russia': ['Moscow', 17_098_246], 'Canada': ['Ottawa', 9_984_670], 'China': ['Beijing', 9_596_961], 'United States': ['Washington, D.C.', 9_525_067], 'Brazil': ['Brasília', 8_515_767]}

print('-'*60, '\n| {:<20} | {:<20} | {:<10} |'.format('Country', 'Capital', 'Area'))
print('-'*60)
for k, v in countries_dict.items():
    region, area = v
    print('| {:<20} | {:<20} | {:<10} |'.format(k, region, area))
print('-'*60)

當前代碼 output:

------------------------------------------------------------ 
| Country              | Capital              | Area       |
------------------------------------------------------------
| Russia               | Moscow               | 17098246   |
| Canada               | Ottawa               | 9984670    |
| China                | Beijing              | 9596961    |
| United States        | Washington, D.C.     | 9525067    |
| Brazil               | Brasília             | 8515767    |
------------------------------------------------------------

所需代碼output(列寬對應最長值的長度等):

----------------------------------------------- 
| Country       | Capital          | Area     |
-----------------------------------------------
| Russia        | Moscow           | 17098246 |
| Canada        | Ottawa           | 9984670  |
| China         | Beijing          | 9596961  |
| United States | Washington, D.C. | 9525067  |
| Brazil        | Brasília         | 8515767  |
-----------------------------------------------

方法不多。 為了能夠知道列寬,您首先需要讀取數據並計算每列的適當寬度。

只有這樣您才能生成表格。

這是一個幼稚的實現:

def mktable(dic, header=None):
    # get max col width
    col_widths = list(map(max, zip(*(map(lambda x: len(str(x)), (k,*v))
                                     for k,v in dic.items()))))

    # default numeric header if missing
    if not header:
        header = range(1, len(col_widths)+1)
    
    header_widths = map(lambda x: len(str(x)), header)
    
    # correct column width if headers are longer
    col_widths = [max(c,h) for c,h in zip(col_widths, header_widths)]
    
    # create separator line
    line = '+%s+' % '+'.join('-'*(w+2) for w in col_widths)
    #line = '-' * (sum(col_widths)+(len(col_widths)-1)*3+4)
    
    # create formating string
    fmt_str = '| %s |' % ' | '.join(f'{{:<{i}}}' for i in col_widths)
    
    # header
    print(line)
    print(fmt_str.format(*header))
    print(line)
    
    # data
    for k, v in countries_dict.items():
        print(fmt_str.format(k, *v))
    
    # footer
    print(line)
mktable(countries_dict, header=('Country', 'Capital', '----- Area -----'))

output:

+---------------+------------------+------------------+
| Country       | Capital          | ----- Area ----- |
+---------------+------------------+------------------+
| Russia        | Moscow           | 17098246         |
| Canada        | Ottawa           | 9984670          |
| China         | Beijing          | 9596961          |
| United States | Washington, D.C. | 9525067          |
| Brazil        | Brasília         | 8515767          |
+---------------+------------------+------------------+

暫無
暫無

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

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