繁体   English   中英

根据 python 中终端的大小在有序列中打印列表

[英]Print a list in ordered columns based on the size of the terminal in python

我正在 python 中编写ls版本,以学习如何编程,并在此过程中更加熟悉一些 GNU 工具、操作系统等。

我有点想弄清楚如何将 output 打印到有序列中。 因此,如果我想将所有内容打印到列中,我可以尝试以下解决方案:

lfile = len(max(ordered,key=len))
padding = 5
total = w // (lfile + padding)
# This code is inside a loop that iterates the list

 lfile = len(max(ordered,key=len))
 print(f'{inode:<1}{blocks:<1} {f:<{lfile}} ', end='')
 if (ordered.index(f) + 1) % total == 0:
     print("")

这将产生一个 output 像这样:

   00    01    02    03    04    05    06    07    08    09    10    11    12 
   13    14    15    16    17    18    19    20 

这仍然不完全正确,但为了争论,我想展示我所追求的解决方案。

问题是后来我意识到ls将 output 排列成这样的字母列:

00  02  04  06  08  10  12  14  16  18  20
01  03  05  07  09  11  13  15  17  19

因此解决这个问题变得更加棘手,特别是考虑到您需要根据终端的元素数量和宽度动态更改列数。

如果我的问题正确,这可能会有所帮助。

# columns per line
columns = 8

# space for each number
space = 8

# current column printed
column_index = 0

# our list of numbers
numbers = list(range(1, 31))

# outputs a string with specific length
def blank(string, space):
    return (string + " " * (space - len(string)))[:space]

# output number list
while numbers:
    # pop first element of list
    num = numbers.pop(0)

    # print spaced number
    # next print will be in same line
    print( blank( str(num), space), end="" )

    # increment column index
    column_index += 1

    # if we hit out column limit
    if column_index % columns == 0:
        # print end of line
        print()

# if we didn't hit column limit at last print
# print end of line
if column_index % columns:
    print()

您也可以简单的列表迭代而不是弹出:

numbers = list(range(1, 31))

for num in numbers:
    # some code

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM