我要做的是从嵌套数组中生成一个对正列作为标题状态。但我就是想不出怎么办。这就是数组。。你知道吗
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行的代码神奇地完成。我真的很想看到这样的答案(这是我会接受的正确答案),但请解释任何奇怪的语法。但如果你只是想增加我已经存在的工作,这将是伟大的,以及我更容易。你知道吗
我是按照你的编辑来编辑的。您可以这样做来坚持基本原则:
谢谢你的回答。它们都很好地工作我只是张贴这个答案,因为我想合并成一个两者的努力的一部分。你知道吗
您可以^{} 子列表,这样就可以得到值的三元组。然后可以将这些值格式化为宽度为8、5、5的列,右对齐,并用空格填充(请参见pyformat.info):
要获得更一般的答案,可以获取每列的最大宽度,并为每种宽度创建一个格式字符串:
相关问题 更多 >
编程相关推荐