Python:证明嵌套数组的列

时间:2017-01-29 01:16:44

标签: python arrays python-3.x justify

我想要做的是从嵌套数组中创建一个对齐的列作为标题状态。但是,我无法弄清楚如何将其拉下来。所以这是阵列..

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行神奇地做到这一点。我真的很想看到那种答案(我接受的那种答案是正确的答案),但请解释任何奇怪的语法。但是,如果你只想添加我已经存在的工作,这对我来说也会更好,也更容易。

3 个答案:

答案 0 :(得分:0)

您可以zip子列表,这样您就可以获得三元组值。然后,您可以将值格式化为宽度为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))

答案 1 :(得分:0)

我根据你的编辑编辑了它。你可以坚持基础:

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("")

答案 2 :(得分:0)

感谢您的回答。它们都很完美我只发布这个答案,因为我想将两者的部分努力合并为一个。

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('')