Python: 嵌套数组的列对齐

2024-09-29 03:34:06 发布

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

我要做的是从嵌套数组中生成一个对正列作为标题状态。但我就是想不出怎么办。这就是数组。。你知道吗

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

这就是我想要实现的(注意对齐):

  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

我能够创建代码来成功地证明每个子数组的正确性,但我的结果只是垂直的。主要是因为我还没有找到代码来把它分成行和列,所以我只有一个很长的单列。我的结果如下:

  apples
 oranges
cherries
  banana
Alice
  Bob
Carol
...#you get the picture

编辑: 所以我的问题很简单,假设你还不知道数组的元数据,我怎么把它分成3个不同的列,例如(子数组的数量)

如果你想看我的源代码,它在这里。。。你知道吗

#function to get the longest word in the sub-array
#to determine justification length
def maxLength(someList):
    count = {}
    max_num = 0
    for item in someList:
        count[item] = len(item)
    for value in count.values():
        if value > max_num:
            max_num = value
    return(max_num)

#function to store the length of the longest words 
#of each sub-array into an array
def maxWidths(tableData):
    widths = []
    for i in range(len(tableData)):
        widths.insert(i,maxLength(tableData[i]))
    return(widths)

#function to print table(this is the part that needs work)                      
def printTable(tableData):
    widths = maxWidths(tableData)
    for i in range(len(tableData)):
        for item in tableData[i]:
            print(item.rjust(widths[i]))

我只是把我的代码放在里面以提供帮助,但我相信有些人可以用不到10行的代码神奇地完成。我真的很想看到这样的答案(这是我会接受的正确答案),但请解释任何奇怪的语法。但如果你只是想增加我已经存在的工作,这将是伟大的,以及我更容易。你知道吗


Tags: theto代码infor数组itemnum
3条回答

我是按照你的编辑来编辑的。您可以这样做来坚持基本原则:

from __future__ import print_function

tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
max_width=[]
for i in tableData:
    width=[]
    for obj in range(0,len(i)):
        width.append(len(i[obj])) #adds the len(i[obj])
    max_width.append(max(width)) #appends the length of longest str of the column

max_height = max(len(i) for i in tableData) #Finds the max height of the array

for obj in range(0,max_height): #obj is the number of item in a row
    for index, i in enumerate(tableData): #i a single column in tableData
        try: #Just in case if one of the rows has fewer item than the rest
            print ("{0:>{1}}".format(i[obj], max_width[index]+1), end="") #prints it with the proper formatting
        except:
            pass
    print("")

谢谢你的回答。它们都很好地工作我只是张贴这个答案,因为我想合并成一个两者的努力的一部分。你知道吗

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

#function to get an array of the length of the longest words
def Widths(tableData):
    widths = [len(max(column, key=len)) for column in tableData]
    return(widths)

#function to print table                      
def printTable(tableData):
    widths = Widths(tableData)
    for i in range(len(tableData[0])):
        for j in range(len(tableData)):
            try:
                print(tableData[j][i].rjust(widths[j]), end = ' ')
            except:
                pass
        print('')

您可以^{}子列表,这样就可以得到值的三元组。然后可以将这些值格式化为宽度为8、5、5的列,右对齐,并用空格填充(请参见pyformat.info):

for fruit, person, animal in zip(*tableData):
   print('{: >8} {: >5} {: >5}'.format(fruit, person, animal))

要获得更一般的答案,可以获取每列的最大宽度,并为每种宽度创建一个格式字符串:

widths = [max(len(value) for value in column) for column in tableData]
line = ' '.join('{{: >{width}}}'.format(width=width)
                for width in widths)
for row in zip(*tableData):
    print(line.format(*row))

相关问题 更多 >