如何在使用prettytable时获取单元格的值

时间:2014-06-23 12:13:49

标签: python prettytable

使用prettytable时是否可以获取特定单元格的值?

我有以下代码来遍历简单表的所有行。

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    print(row)

此示例打印以下3个表:

+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    A     |    B     |    C     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    F     |    O     |    O     |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
|    B     |    A     |    R     |
+----------+----------+----------+

如何才能获得一行Column 1Column 2Column 3的值?

1 个答案:

答案 0 :(得分:5)

看起来你想要做的是从documentation here获取数据的子集,尝试:

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    print row.get_string(fields=["Column 1"]) # Column 1

编辑:看起来你不想要标题或边框,只是值,在这种情况下,这应该有效:

from prettytable import PrettyTable

table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])

for row in table:
    row.border = False
    row.header = False
    print row.get_string(fields=["Column 1"]).strip() # Column 1