如何在python中垂直更改对齐列?

时间:2019-07-23 04:07:32

标签: python python-3.x

我有两个列表:

team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']

我想显示这些列表的内容,如下所示:

team1(bold)     team2(bold)
Valentine       The Aviator
Consus          Iley
Never Casual    Nisquick
Nuclear         Dragoon
Daltwon         WAACK

我希望代码能够处理多个列表。

我目前已经尝试了这段代码,几乎可以正常工作,但是我不确定如何配置它,以便第一列之后的列对齐。

L = [team1,team2]
max_length = max(map(len, L))  # finding max length
output = zip(*map(lambda x: x + [' '] * (max_length - len(x)), L))  # filling every sublist with ' ' to max_length and then zipping it
for i in output: print(*i, sep= '                  ')

输出:

Valentine                   The Aviator
Consus                 Iley
Never Casual                  Nisquick
NucIear                  Dragoon
Daltwon                   WAACK

4 个答案:

答案 0 :(得分:1)

使用string formatting

team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']

for t1, t2 in zip(team1, team2):
    print('%-20s %s' % (t1, t2))

输出:

Vàlentine            The Aviator
Consus               Iley
Never Casual         Nisquick
NucIear              Dragoon
Daltwon              WAACK

答案 1 :(得分:0)

您可以在python中使用ljust函数。 此函数使您可以在字符串中添加一定数量的空格。因此,知道第一个字符串的最大长度(粗略估算)后,就可以像这样格式化它。

string.ljust(max_len)

示例

"hi".ljust(10) will give you "hi        "

"hello".ljust(10) will give you "hello     "

如果您希望内容在右侧对齐,也可以使用rjust。

答案 2 :(得分:0)

如果您使用python3,则还可以使用fstring进行格式化:)

team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']
maxlen = max(map(len,team1)) + 1 
for a,b in zip(team1,team2):
    print(f"{a: <{maxlen}} {b}")

给予

Vàlentine      The Aviator
Consus         Iley
Never Casual   Nisquick
NucIear        Dragoon
Daltwon        WAACK

答案 3 :(得分:0)

我对您的代码进行了一些修改,并计算了每行打印行所需的空间数:

team1 = ['Vàlentine', 'Consus', 'Never Casual ', 'NucIear', 'Daltwon']
team2 = ['The Aviator', 'Iley', 'Nisquick', 'Dragoon', 'WAACK']
max_length = max(map(len, team1))  # finding max length
for (t1,t2) in zip(team1,team2):
    numOfSpace = max_length - len(t1) + 5 # 5 is the minimum space, you can change it
    space = ""
    for i in range(numOfSpace):
        space = space+ " "
    print(t1, space, t2)

输出:

Vàlentine           The Aviator
Consus              Iley
Never Casual        Nisquick
NucIear             Dragoon
Daltwon             WAACK