3

私はコマンドラインインタープリターに取り組んでおり、文字列の長いリストを読みやすい方法で出力する機能を持っています。

機能は次のとおりです。

def pretty_print(CL_output):
    if len(CL_output)%2 == 0:
        #even
        print "\n".join("%-20s %s"%(CL_output[i],CL_output[i+len(CL_output)/2]) for i in range(len(CL_output)/2))    
    else:
        #odd
        d_odd = CL_output + ['']
        print "\n".join("%-20s %s"%(d_odd[i],d_odd[i+len(d_odd)/2]) for i in range(len(d_odd)/2))

したがって、次のようなリストの場合:

myList = ['one','potato','two','potato','three','potato','four','potato'...]

関数 pretty_print は以下を返します。

pretty_print(myList)

>>> one                  three
    potato               potato
    two                  four
    potato               potato

ただし、より大きなリストの場合、関数 pretty_print はリストを 2 列で出力します。リストのサイズに応じて 3 列または 4 列にリストを出力するように pretty_print を変更する方法はありますか? したがって、len(myList) ~ 100 の場合、pretty_print は 3 行で出力され、len(myList) ~ 300 の場合、pretty_print は 4 列で出力されます。

だから私が持っている場合:

  myList_long = ['one','potato','two','potato','three','potato','four','potato'...
           'one hundred`, potato ...... `three hundred`,potato]

望ましい出力は次のとおりです。

pretty_print(myList_long)

>>> one                  three                one hundred          three hundred
    potato               potato               potato               potato
    two                  four                 ...                  ...
    potato               potato               ...                  ....
4

2 に答える 2

2
于 2013-11-08T16:29:41.530 に答える
0

入力として端末の幅も取り、それに収まる数の列だけを表示するソリューションがあります。参照: https://gist.github.com/critiqjo/2ca84db26daaeb1715e1

col_print.py

def col_print(lines, term_width=80, indent=0, pad=2):
  n_lines = len(lines)
  if n_lines == 0:
    return

  col_width = max(len(line) for line in lines)
  n_cols = int((term_width + pad - indent)/(col_width + pad))
  n_cols = min(n_lines, max(1, n_cols))

  col_len = int(n_lines/n_cols) + (0 if n_lines % n_cols == 0 else 1)
  if (n_cols - 1) * col_len >= n_lines:
    n_cols -= 1

  cols = [lines[i*col_len : i*col_len + col_len] for i in range(n_cols)]

  rows = list(zip(*cols))
  rows_missed = zip(*[col[len(rows):] for col in cols[:-1]])
  rows.extend(rows_missed)

  for row in rows:
    print(" "*indent + (" "*pad).join(line.ljust(col_width) for line in row))
于 2015-06-16T08:06:49.810 に答える