Python Tabulate代码仅输出表头,请求定位断点问题
基因型计算代码仅输出表头问题排查
问题概述
编写Python代码计算约200代基因型,当BB基因值(变量z)大于0.99时停止运行。当前代码仅输出Tabulate生成的表头,无后续世代数据,需定位问题并修复。
代码问题定位
你的代码逻辑本身无错误,但存在两个关键输出问题:
- 循环内生成的表格未写入文件:循环中调用
tabulate(table, ...)生成了每一代的数据表格,但没有将结果写入outputFile,导致除表头外无其他内容输出。 - 表头写入后未换行:表头写入文件时未添加换行符,即使后续写入内容也会和表头连在一起,影响可读性。
修复后的代码
from tabulate import tabulate outputFile = open("genotype.txt", 'w') x = 0.25 y = 0.5 z = 0.25 g = 1 t = [["Generation", "AA Gene", "AB Gene", "BB Gene"]] # 写入表头并添加换行 outputFile.write(tabulate(t) + "\n") while z < 0.99: table = [[g, x, y, z]] # 生成表格内容并写入文件,添加换行 outputFile.write(tabulate(table, floatfmt=("10.0f", "7.3f", "7.3f", "7.3f")) + "\n") p = 0.5 * (y / (y + z)) x = p * p y = (2*p) * (1-p) z = (1-p) * (1-p) g = g+1 outputFile.close()
额外优化建议
使用with语句管理文件,避免忘记关闭文件或异常场景下文件未正常关闭:
from tabulate import tabulate x = 0.25 y = 0.5 z = 0.25 g = 1 t = [["Generation", "AA Gene", "AB Gene", "BB Gene"]] with open("genotype.txt", 'w') as outputFile: outputFile.write(tabulate(t) + "\n") while z < 0.99: table = [[g, x, y, z]] outputFile.write(tabulate(table, floatfmt=("10.0f", "7.3f", "7.3f", "7.3f")) + "\n") p = 0.5 * (y / (y + z)) x = p * p y = (2*p) * (1-p) z = (1-p) * (1-p) g = g+1
内容的提问来源于stack exchange,提问作者TheCodeGoblin
相关产品推荐
相关产品推荐

