如何在Python表格中合并/合并表?

狼 :

tabulate这里找到它之后,我一直在使用Python 模块

从文件中读取文件时,与其在单独的框上分开,不如将其合并/合并?

这是示例代码和输出。

wolf@linux:~$ cat file.txt 
Apples
Bananas
Cherries
wolf@linux:~$ 

Python代码

wolf@linux:~$ cat script.py 
from tabulate import tabulate

with open(r'file.txt') as f:
    for i,j in enumerate(f.read().split(), 1):
        table = [[ i,j ]]
        print(tabulate(table, tablefmt="grid"))
wolf@linux:~$ 

输出量

wolf@linux:~$ python script.py 
+---+--------+
| 1 | Apples |
+---+--------+
+---+---------+
| 2 | Bananas |
+---+---------+
+---+----------+
| 3 | Cherries |
+---+----------+
wolf@linux:~$ 

期望的输出

wolf@linux:~$ python script.py 
+---+----------+
| 1 | Apples   |
+---+----------+
| 2 | Bananas  |
+---+----------+
| 3 | Cherries |
+---+----------+
wolf@linux:~$ 
rdas:

您应该创建一个表格并打印,而不是创建table3次并每次打印:

from tabulate import tabulate

with open(r'temp.txt') as f:
    table = []
    for i,j in enumerate(f.read().split(), 1):
        table.append([ i,j ])
    print(tabulate(table, tablefmt="grid"))

结果:

+---+----------+
| 1 | Apples   |
+---+----------+
| 2 | Bananas  |
+---+----------+
| 3 | Cherries |
+---+----------+

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章