简体   繁体   English

如何垂直打印数字列表?

[英]How do I print a list of numbers vertically?

I am trying to solve an exercise.我正在尝试解决一个练习。 I should write a function that takes a list of integers, converts it to a string of numbers displayed vertically.我应该写一个 function,它接受一个整数列表,将其转换为垂直显示的数字字符串。

mylist = [5,69,2090]

the function should return/print the following string: function 应该返回/打印以下字符串:

    2
    0
  6 9
5 9 0

I tried to solve it with the following code, but it doesn't help me我试图用下面的代码解决它,但它对我没有帮助

def printstring(mylist):
    h = len(mylist)//3
    for i in range(h):
        print(mylist[i],mylist[h+i],l[h+i+1])
lst = [5,69,2090]

n = max(len(str(i)) for i in lst)
for i in zip(*['{:>{n}}'.format(i, n=n) for i in lst]):
    print(' '.join(i))

Prints:印刷:

    2
    0
  6 9
5 9 0

For lst = [1,123,12,12345,1234] :对于lst = [1,123,12,12345,1234]

      1  
      2 1
  1   3 2
  2 1 4 3
1 3 2 5 4

First convert your list items to a string then find the maximum length.首先将您的列表项转换为字符串,然后找到最大长度。 Pad your strings to fit that length and print them:填充您的字符串以适合该长度并打印它们:

lst = [5, 69, 2090]
lst = list(map(str, lst))
max_lenght = max(map(len, lst))
padded_lst = [item.rjust(max_lenght, " ") for item in lst]
for row in zip(*padded_lst):
    print(" ".join(row))
    2
    0
  6 9
5 9 0

I'd apply a few steps here.我会在这里应用几个步骤。 First, determine the maximum length of digits for each number by converting them to strings.首先,通过将数字转换为字符串来确定每个数字的最大数字长度。 Secondly, left pad each number string to that length using rjust .其次,使用rjust将每个数字字符串左填充到该长度。 Finally, rotate the matrix 90 degrees using the classic zip(*m) trick and join it all back into a printable square.最后,使用经典的zip(*m)技巧将矩阵旋转 90 度并将其全部连接回一个可打印的正方形。

>>> lst = [5,69,2090]
>>> size = max(map(len, map(str, lst)))
>>> m = [str(x).rjust(size, " ") for x in lst]
>>> print("\n".join([" ".join(x) for x in zip(*m)]))
    2
    0
  6 9
5 9 0

A not so much readable two liner不太可读的两行

sl = ['{:>{}d}'.format(s, len(str(max(mylist)))) for s in mylist]
print('\n'.join(' '.join(s) for s in zip(*sl))) 

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

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