打印整洁的列表/表中的列表列表

问题描述 投票:0回答:2

我有一个列表的列表,结构为[[s: str, s: str, s: str]],其中可以有任意数量的项目(列表)。

我想像这样在列中干净地打印它:

FirstFirst     FirstSecond    FirstThird
SecondFirst    SecondSecond   SecondThird
ThirdFirst     ThirdSecond    ThirdThird
foo            bar            foobar

因此,尽管长度不同,但子列表中的每个项目在列中都左对齐。

我已经尝试过非常复杂的列表理解,例如

lists = [['FirstFirst', 'FirstSecond', 'FirstThird'],
         ['SecondFirst', 'SecondSecond', 'SecondThird'],
         ['ThirdFirst', 'ThirdSecond', 'ThirdThird'],
         ['foo', 'bar', 'foobar']]

[print(f'{_[0]}{" " * (15 - len(_[0]))}{_[1]}{" " * (30 - len(_[0] + _[1] + " " * (15 - len(_[0]))))}{_[2]}') for _ in lists]

虽然这确实起作用,但它非常残酷。

更糟糕的是,这种列表理解根本无法扩展。如果要向子列表中的每个项目添加另一个字符串,则必须在列表理解中添加更多内容,以使所有内容仍然有效。另外,如果我希望两个列表具有不同的长度,那么一切都会被挫败。

什么是更好的方法?

python python-3.x list list-comprehension nested-lists
2个回答
1
投票

您需要计算每个单词的长度(在每一列中)。获得单词的最大长度很简单:

data = [['FirstFirst', 'FirstSecond', 'FirstThird'],
         ['SecondFirst', 'SecondSecond', 'SecondThird'],
         ['ThirdFirst', 'ThirdSecond', 'ThirdThird'],
         ['foo', 'verylongwordinsidehere', 'bar', ]]    # changed to a longer one


# get max word length
max_len = max(len(i) for j in data for i in j)

# do not use list comp for printing side effect - use a simple loop
for inner in data:
    for word in inner:
        print(f"{word:{max_len}}",end=" | ") # and format the length into it
    print()

获取

FirstFirst             | FirstSecond            | FirstThird             | 
SecondFirst            | SecondSecond           | SecondThird            | 
ThirdFirst             | ThirdSecond            | ThirdThird             | 
foo                    | verylongwordinsidehere | bar                    | 

这看起来有点难看,如果您只获得每列最大长度的恕我直言会更好:

# transpose the list, get the max of each column and store in as dict[column]=legnth
col_len = {i:max(map(len,inner)) for i,inner in enumerate(zip(*data))}

# print(col_len) # {0: 11, 1: 22, 2: 11}

# print using the column index from enumerate to lookup this columns lenght
for inner in data:
    for col,word in enumerate(inner):
        print(f"{word:{col_len[col]}}",end=" | ")
    print()

获得调整列宽的输出:

FirstFirst  | FirstSecond            | FirstThird  | 
SecondFirst | SecondSecond           | SecondThird | 
ThirdFirst  | ThirdSecond            | ThirdThird  | 
foo         | verylongwordinsidehere | bar         | 

请参阅


0
投票

使用理解:

# first map each string to formatted string with white space 
lists = [list(map(lambda item: f'{item:<20}', inner_list)) for inner_list in lists]
#then join them 
lists = [''.join(item) for item in lists]
print('\n'.join(lists))

这里唯一的问题是20不能是变量,需要硬编码

© www.soinside.com 2019 - 2024. All rights reserved.