2

我有一个函数接受列表作为已经从另一个函数创建的参数。该列表以列行格式打印。此函数应假定列表中的第一项包括列标题,并且列表的其余部分包括值。该showList()函数应该能够整齐地显示由空格或制表符分隔的 2 到 5 列的列表。在大多数情况下,它运作良好,但当它有多个国家要列出时,它只列出一个。这是它的外观示例:

Country  Gold   Silver Bronze
(this space is actually a sequence of equal signs to represent a heading line)
United States 765    555    780
Great Britain 600  200      950
def showList(returned_List):
    header = '     '
    line = ''
    entries = ''
    for i in returned_List[0]:
        header += i + (' ')*5
    for k in range(len(header)):
        line += '='
    for j in returned_List[1]:
        entries += j +(' ')*5
    print(header, '\n', line, '\n', entries)
    return(returned_List)
4

2 回答 2

1

您需要做的就是遍历 中的行returned_list,而不是硬编码returned_list[0]

def showList(returned_List):
    header = '     '
    line = ''
    entries = ''
    for row in returned_list:
        for i in row:
            header += i + (' ')*5
        for k in range(len(header)):
            line += '='
        for j in returned_List[1]:
            entries += j +(' ')*5
        print(header, '\n', line, '\n', entries)
        return(returned_List)

从你的评论,我有点明白你在找什么。这是我不久前写的脚本的改编,可以帮助你:

def tabularize(inData, outfilepath):
    """ Return nothing
        Write into the file in outfilepath, the contents of inData, expressed in tabular form.
        The tabular form is similar to the way in which SQL tables are displayed.
    """

    widths = [max([len(row) for row in rows])+2 for rows in izip_longest(*inData, fillvalue="")]

    with open(outfilepath, 'w') as outfile:
        outfile.write("+")
        for width in widths:
            outfile.write('-'*width + "+")
        outfile.write('\n')
        for line in lines:
            outfile.write("|")
            for col,width in izip_longest(line,widths, fillvalue=""):
                outfile.write("%s%s%s|" %(' '*((width-len(col))/2), col, ' '*((width+1-len(col))/2)))
            outfile.write('\n+')
            for width in widths:
                outfile.write('-'*width + "+")


outfile.write('\n')

if __name__ == "__main__":
    print 'starting'

    tabularize(infilepath, outfilepath, '...', False)

    print 'done'

希望这可以帮助

于 2013-07-18T21:24:47.620 回答
0

for i in returned_list[0]: 只查看第一个条目。

你可能想要:

对于返回列表中的 i:

于 2013-07-18T21:27:07.163 回答