列中显示的嵌套列表

2024-09-29 03:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将嵌套列表显示为列。所以我正在处理的数据是:

tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]

我想显示为

^{pr2}$

以便条目右对齐。我已经看过Create nice column output in python,但是我不能实现类似的结果。我目前掌握的代码是:

tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]

total_len= [[] for x in range(len(tableData))]
longest_string = []

for y1 in range(0, len(tableData)):
    for y2 in range(0, len(tableData[y1])):       
        total_len[y1].append(len(tableData[y1][y2]))

for y1 in range(0, len(total_len)):    
    longest_string.append(max(total_len[y1]))

for y1 in range(len(tableData)):
    for y2 in range(len(tableData[y1])):
        print("".join(tableData[y1][y2].rjust(longest_string[y1])))

Tags: inforstringlenlongestrangetotalbanana
3条回答

没有第三方熊猫的类似格式:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

# Find the max length of the word in each row
lens = [max(len(col) for col in row) for row in tableData]

# zip(*list) transposes a list...rows become columns
for row in zip(*tableData):
    # Pass the column widths dynamically.
    print('{:>{lens[0]}} {:>{lens[1]}} {:>{lens[2]}}'.format(*row,lens=lens))

输出:

^{pr2}$

编辑

以下是一个可以动态显示任意数量的行和列的版本:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

# Find the max length of the word in each row
lens = [max(len(col) for col in row) for row in tableData]

# build a format string with an entry for each column
rowfmt = '{:>{}} ' * len(tableData)

# zip(*list) transposes a list...rows become columns
for row in zip(*tableData):
    # Pass the values and column widths dynamically.
    # The zip pairs up each datum with its column width, but in tuples.
    # For example, [data1,data2],[width1,width2] -> [(data1,width1),(data2,width2)]
    # itertools.chain flattens the list of tuples.
    # For example, above becomes [data1,width1,data2,width2]
    print(rowfmt.format(*itertools.chain(*zip(row,lens))))

来自链接线程的^{}solution

>>> for row in zip(*tableData):
...     print("{: >10} {: >10} {: >10}".format(*row))
... 
    apples      Alice       dogs
   oranges        Bob       cats
  cherries      Carol      moose
    banana      David      goose

虽然我更喜欢"pandas" dataframe based solution。在

我不知道你有一个^{}但如果你有,那就很容易了。您可以创建dataframe,然后使用^{}方法:

import pandas as pd
tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']]
df = pd.DataFrame(tableData).T

In [224]: df
Out[224]: 
          0      1      2
0    apples  Alice   dogs
1   oranges    Bob   cats
2  cherries  Carol  moose
3    banana  David  goose

result = df.to_string(index=False, header=False)

In [228]: print(result)
   apples  Alice   dogs
  oranges    Bob   cats
 cherries  Carol  moose
   banana  David  goose

相关问题 更多 >