简体   繁体   中英

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

I am writing a version of ls in python to learn how to program and in the process get more familiar with some GNU tools, the OS, etc.

I am a little stuck in trying to figure out how to print the output into ordered columns. So if I wanted to print everything into columns I could try a solution along this line:

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

That would yield an output like this:

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

Which is still not entirely right, but for the sake of argument, I wanted to show the solution I was pursuing.

The problem is that later I realised that ls arranges the output into alphabetical columns like this:

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

so it makes this more tricky to solve, especially considering that you need to dynamically alter the number of columns depending on number of elements and width of your terminal.

If I get your question right, this might help.

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

You can also you simple list iteration instead of poping:

numbers = list(range(1, 31))

for num in numbers:
    # some code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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