[英]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.