![如何将 python 中的表格输出打印到 latex 中?](https://linux22.com/image/445243/%E5%A6%82%E4%BD%95%E5%B0%86%20python%20%E4%B8%AD%E7%9A%84%E8%A1%A8%E6%A0%BC%E8%BE%93%E5%87%BA%E6%89%93%E5%8D%B0%E5%88%B0%20latex%20%E4%B8%AD%EF%BC%9F.png)
答案1
如果您控制创建当前输出的打印语句,那么您也可以编写打印语句来生成 LaTeX 代码。简单示例:
Python:
headers = ["x 1","x 2","x 3","x 4","x 5","bbar"]
data = dict()
data["x 4"] = [1,2,3,1,0,9]
data["x 5"] = [3,2,2,0,1,15]
data["z"] = [1,9,3,0,0,0]
textabular = f"l|{'r'*len(headers)}"
texheader = " & " + " & ".join(headers) + "\\\\"
texdata = "\\hline\n"
for label in sorted(data):
if label == "z":
texdata += "\\hline\n"
texdata += f"{label} & {' & '.join(map(str,data[label]))} \\\\\n"
print("\\begin{tabular}{"+textabular+"}")
print(texheader)
print(texdata,end="")
print("\\end{tabular}")
生成的 LaTeX 代码:
\begin{tabular}{l|rrrrrr}
& x 1 & x 2 & x 3 & x 4 & x 5 & bbar\\
\hline
x 4 & 1 & 2 & 3 & 1 & 0 & 9 \\
x 5 & 3 & 2 & 2 & 0 & 1 & 15 \\
\hline
z & 1 & 9 & 3 & 0 & 0 & 0 \\
\end{tabular}
输出:
答案2
扩展上述使用打印语句生成 Latex 代码的答案:有一个 Python 库专门latextable
用于执行此操作https://github.com/JAEarly/latextable
这里还有关于如何使用它的指南:https://towardsdatascience.com/how-to-create-latex-tables-directly-from-python-code-5228c5cea09a
全面披露——我是这个图书馆的作者。