修复Python中的错误?

时间:2014-11-14 02:18:11

标签: python list python-3.x formatting

我有一个清单,

L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
['Jane', 'Doe', '3.5', 'CS', '2'], ['Joe', 'Doe', '2.0', 'CpE', '0'],
['Todd', 'Brown', '3.88', 'CS', '5'], 
['Mike', 'Smith', '3.88', 'CS', '5']]

我可以将它打印在如下表格中:

    --------------------------------------------------------
    |     First|      Last|       GPA|     Major|     Drops|
    --------------------------------------------------------
    |      Jane|       Doe|      3.50|        CS|         2|
    |       Joe|       Doe|      2.00|       CpE|         0|
    |      Todd|     Brown|      3.88|        CS|         5|
    |      Mike|     Smith|      3.88|        CS|         5|

我的代码到目前为止:

    L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
     ['Jane', 'Doe', '3.5', 'CS', '2'],
     ['Joe', 'Doe', '2.0', 'CpE', '0'],
     ['Todd', 'Brown', '3.88', 'CS', '5'],
     ['Mike', 'Smith', '3.88', 'CS', '5']]
count1 = 1
while count1 < len(L):
    L[count1][2] = float(L[count1][2])
    L[count1][4] = int(L[count1][4])
    count1 += 1
h_line = 56 * '-'
first_line = "|"
print (h_line)
s = " "
w = 10
for i in range(len(L[0])):
    str1 = (s*(w - len(L[0][i])) + "%s|" % L[0][i])
    first_line = first_line + str1
print(first_line)
print(h_line)
a = 1
while a < len(L):
    second_line = "|"
    for j in range (len(L[a])):
        if type(L[a][j]) == str :
            str2 = (s*(w - len(L[a][j])) + ("%s|" % L[a][j]))
            second_line = second_line + str2
        elif type(L[a][j]) == float :
            str2 = (s*(w-4) + ("%.2f|" % L[a][j]))
            second_line = second_line + str2
        elif type(L[a][j]) == float :
            str2 = (s*(w-1) + ("%i|" % L[a][j]))
            second_line = second_line + str2
    print (second_line)
    a = a + 1


print (h_line)

但我的输出看起来像:

    --------------------------------------------------------
    |     First|      Last|       GPA|     Major|     Drops|
    --------------------------------------------------------
    |      Jane|       Doe|      3.50|        CS|
    |       Joe|       Doe|      2.00|       CpE|
    |      Todd|     Brown|      3.88|        CS|
    |      Mike|     Smith|      3.88|        CS|
    --------------------------------------------------------

我不明白我做错了什么。老乡帮帮我吧!

2 个答案:

答案 0 :(得分:8)

圣洁的问题,这是错误的方式!使用string formatting

L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
     ['Jane', 'Doe', '3.5', 'CS', '2'], ['Joe', 'Doe', '2.0', 'CpE', '0'],
     ['Todd', 'Brown', '3.88', 'CS', '5'], 
     ['Mike', 'Smith', '3.88', 'CS', '5']]

def display_table(rows):
    template = "|{:>10}|{:>10}|{:>10}|{:>10}|{:>10}|"
    horiz_rule = "-" * 56
    header = rows[0]
    print(horiz_rule)
    print(template.format(*header))
    print(horiz_rule)
    for row in rows[1:]:
        print(template.format(*row))
    print(horiz_rule)

display_table(L)

如果您需要以编程方式指定列宽,则可以使用额外的{}来转义外部格式,例如

template = "|{{:>{0}}}".format(some_width) * num_columns + "|"
## if some_width is 10 and num_columns is 5, 
## results in the same template as above. Then you can do:
horiz_rule = 1 + some_width * (num_columns + 1)

作为一个工作示例,也许您希望将每列扩展到最少10个空格,但希望与该列中最长的元素以及1对齐。

def display_table(rows):
    # might want a sanity check here to make sure the table is square
    num_columns = len(rows)
    template = "|{{:>{}}}" * len(rows[0]) + "|"
    header = rows[0]
    # zip(*iterable) is a good recipe for aligning columnwise
    column_lengths = [max(10, max(map(len, col)) + 1) for col in zip(*rows)]
    finished_template = template.format(*column_lengths)
    hr = "-" * (sum(column_lengths) + num_columns + 1)
    print(hr)
    print(finished_template.format(*header))
    print(hr)
    for row in rows[1:]:
        print(finished_template.format(*row))
    print(hr)
display_table(L)

结果:

--------------------------------------------------------
|     First|      Last|       GPA|     Major|     Drops|
--------------------------------------------------------
|      Jane|       Doe|       3.5|        CS|         2|
|       Joe|       Doe|       2.0|       CpE|         0|
|      Todd|     Brown|      3.88|        CS|         5|
|      Mike|     Smith|      3.88|        CS|         5|
--------------------------------------------------------

或者,如果您添加姓氏为&#34; SomeReallyLongName&#34;的学生:

L.append(['Foo','SomeReallyLongName','2.0','Mus','10'])
display_table(L)
## OUTPUT
------------------------------------------------------------------
|     First|               Last|       GPA|     Major|     Drops|
------------------------------------------------------------------
|      Jane|                Doe|       3.5|        CS|         2|
|       Joe|                Doe|       2.0|       CpE|         0|
|      Todd|              Brown|      3.88|        CS|         5|
|      Mike|              Smith|      3.88|        CS|         5|
|       Foo| SomeReallyLongName|       2.0|       Mus|        10|
------------------------------------------------------------------

在计算水平规则时,看起来最后一位有一个错误的错误。这对我来说很好看,但显然它已经关闭了(一个人!)我会把这种情况作为练习给读者留下来。

答案 1 :(得分:2)

只是替代方案,可能不是这样,但可能有用。

  

pip install制表

注意:我在使用pip或easy_install安装时遇到了一些错误。
成功通过下载表格0.7.3.tar.gz来安装它 并使用以下代码安装:python setup.py install


在行动中查看(您的案例):

from tabulate import tabulate

L = [['First', 'Last', 'GPA', 'Major', 'Drops'],
['Jane', 'Doe', '3.5', 'CS', '2'], 
['Joe', 'Doe', '2.0', 'CpE', '0'],
['Todd', 'Brown', '3.88', 'CS', '5'], 
['Mike', 'Smith', '3.88', 'CS', '5']]

print tabulate(L[1:], headers = L[0],tablefmt="grid")

输出:

>>> 
+---------+--------+-------+---------+---------+
| First   | Last   |   GPA | Major   |   Drops |
+=========+========+=======+=========+=========+
| Jane    | Doe    |  3.5  | CS      |       2 |
+---------+--------+-------+---------+---------+
| Joe     | Doe    |  2    | CpE     |       0 |
+---------+--------+-------+---------+---------+
| Todd    | Brown  |  3.88 | CS      |       5 |
+---------+--------+-------+---------+---------+
| Mike    | Smith  |  3.88 | CS      |       5 |
+---------+--------+-------+---------+---------+
>>> 
  

<强>参考书目:
  制表0.7.3:Python包索引http://goo.gl/OkEF5E