Python:对齐嵌套数组的列
Python: Justifying Columns of Nested Arrays
我想做的是如标题所述,从嵌套数组中创建一个对齐的列。但是我只是不知道如何实现它。所以这是数组..
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
我能够创建代码来成功证明每个 sub-arrays 的合理性,但我的结果只是垂直的。主要是因为我还没有想出代码来把它变成行和列,所以我只有一个很长的单列。我的结果如下:
apples
oranges
cherries
banana
Alice
Bob
Carol
...#you get the picture
编辑:
所以我的问题很简单,假设您还不知道数组的元数据,我如何将它分成 3 个不同的列,例如(sub-arrays 的数量)
如果您想查看我的源代码,它就在这里...
#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 行的时间内完成。我真的很想看到那种答案(这是我会接受的正确答案),但请解释任何奇怪的语法。但是,如果你只是想添加到我现有的工作中,那对我来说也很棒而且更容易。
你可以zip
the sublists so you'll get triplets of values. Then you can format the values into columns of width 8, 5, 5, right justified, padded with spaces (see 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))
我根据你的EDIT编辑了它。您可以这样做以坚持基础知识:
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('')
我想做的是如标题所述,从嵌套数组中创建一个对齐的列。但是我只是不知道如何实现它。所以这是数组..
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
我能够创建代码来成功证明每个 sub-arrays 的合理性,但我的结果只是垂直的。主要是因为我还没有想出代码来把它变成行和列,所以我只有一个很长的单列。我的结果如下:
apples
oranges
cherries
banana
Alice
Bob
Carol
...#you get the picture
编辑: 所以我的问题很简单,假设您还不知道数组的元数据,我如何将它分成 3 个不同的列,例如(sub-arrays 的数量)
如果您想查看我的源代码,它就在这里...
#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 行的时间内完成。我真的很想看到那种答案(这是我会接受的正确答案),但请解释任何奇怪的语法。但是,如果你只是想添加到我现有的工作中,那对我来说也很棒而且更容易。
你可以zip
the sublists so you'll get triplets of values. Then you can format the values into columns of width 8, 5, 5, right justified, padded with spaces (see 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))
我根据你的EDIT编辑了它。您可以这样做以坚持基础知识:
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('')