从列表中创建的表不显示所有元素

时间:2013-07-18 21:18:28

标签: python list file printing

我有一个函数接受列表作为已经从另一个函数创建的参数。列表以列行格式打印。此函数应假定列表中的第一项包括列标题,列表的其余部分包括值。 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)

2 个答案:

答案 0 :(得分: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'

希望这有帮助

答案 1 :(得分:0)

对于i返回_ [0]中的

:仅查看第一个条目。

你可能想要:

对于i返回_list中的