我正在尝试制定一个函数,它接受字符串列表的列表,并将其显示在一个组织良好的表中,其中每一列都右对齐。假设所有内部列表都将包含相同数量的字符串。例如,该值可能如下所示:
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
使用给定的提示,我得出了以下结论:
def printable(tableData):
newTable = np.zeros((len(tableData[0]),len(tableData)))
colWidths = [0] * len(tableData)
for i in range(0,len(tableData)):
colWidths[i] = max(tableData[i], key=len)
largest = max(colWidths, key=len)
for i in range(0,len(tableData)):
for j in range(0,len(tableData[0])):
newTable[i][j] = tableData[j][i].rjust(len(largest))
我对“不”感到震惊。for循环。作为一个初学者,我还没有走出“for-loop”模式。另外,我正在思考解决这个问题的最好的攻击形式。谢谢。
发布于 2018-08-21 03:38:37
tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
# Determine maximum column width
colWidth = 0
for x in tableData:
colWidth = max(colWidth, len(max(x, key=len)))
# Use zip to "flip" your rows and columns
# Note that the * first unpacks your list of lists
for row in zip(*tableData):
# Join each row element together into a string, right justifying each element to your column width as you go
print ''.join([ele.rjust(colWidth) for ele in row])
https://stackoverflow.com/questions/51937095
复制相似问题