修改多列Python的打印函数

2024-05-15 11:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个命令行解释器,我有一个函数,可以以一种易读的方式打印出一长串字符串。在

其功能是:

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))

因此,对于以下列表:

^{pr2}$

函数pretty_print返回:

pretty_print(myList)

>>> one                  three
    potato               potato
    two                  four
    potato               potato

但是,对于较大的列表,函数pretty_print仍然以两列的形式输出列表。有没有办法修改pretty_print,让它根据列表的大小打印出3列或4列的列表?所以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               ...                  ....

Tags: 函数列表outputlenclprettyonepotato
2条回答

我有一个解决方案,它也将终端宽度作为输入,并且只显示可以容纳的列。参见:https://gist.github.com/critiqjo/2ca84db26daaeb1715e1

列_打印.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))

this answer修改。在

def pretty_print(CL_output):
    columns = len(CL_output)//200+2
    lines = ("".join(s.ljust(20) for s in CL_output[i:i+columns-1])+CL_output[i:i+columns][-1] for i in range(0, len(CL_output), columns))
    return "\n".join(lines)

相关问题 更多 >