5

使用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 1的值?Column 2Column 3

4

2 回答 2

7

看起来您想要做的是从此处的文档中获取数据的子集,尝试:

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
于 2014-06-23T13:15:36.360 回答
0

您可以使用 rows 方法来访问原始数据

table.rows[0][0]   # ="A"
于 2022-01-10T13:52:50.933 回答