如何在递归 table 中插入一行和一列

How to insert a row and a column in a recursive table

我发布这个问题是因为我试了一遍又一遍都没有结果。 我写了一个 table,它在 Python 2.7 的 shell 中打印,并将嵌套 for 循环中给出的输入导出到 CSV。我遇到了一些麻烦,因为我需要在 shell 和 CSV 上显示循环使用的初始值。实际上,我需要显示包含 t 假定的所有可能值(即 8)的第一行,并添加包含 s 假定的相应值(即 15)的第一列。由于 Python 命令 printwr.writerow 管理 table 的行,我不知道如何解决这个问题。这是代码:

import csv
with open('chill.csv', 'wb') as f:
    wr = csv.writer(f)
    data = ([str(13.127 + 0.6215 * t - 11.362 * s ** 0.16 + 0.396 * t * s ** 0.16)
                 for t in range(-25, 15, 5)]
                     for s in range(0, 75, 5))
    for row in data:
        print('\t'.join(row))
        wr.writerow(row)

希望大家帮帮忙!

随着您的进展生成文件的解决方案,而不是尝试生成包含所有列表的 data 变量。

import csv

# For readability, extract the cell calculation
def calc_cell(t, s)
    return 13.127 + 0.6215 * t - 11.362 * s ** 0.16 + 0.396 * t * s ** 0.16

with open('chill.csv', 'wb') as f:
    wr = csv.writer(f)

    def add_row(row):
        "Add a new row to both console and file"
        row = map(str, row)  # Coerce values to str, for join
        print('\t'.join(row))
        wr.writerow(row)

    # Add the "header row"
    add_row([' '] + range(-25, 15, 5))

    # Create the table, one row at a time
    for s in range(0, 75, 5):
        add_row([s] + [calc_cell(t,s) for t in range(-25, 15, 5)])