python - 如何在递归表中插入行和列

标签 python python-2.7 export-to-csv

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

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)])

关于python - 如何在递归表中插入行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34009437/

相关文章:

python - 使用 Python 2.7 未将数据插入到 Sqlite3 数据库中

python-2.7 - 如何将对列表(到矩阵)转换为热图; Python

python - 从文本文件中提取特定单词及其后的值

r - 在 R 中,将每个嵌套的数据框写入 CSV

python - 调用 Python 文件后 Excel CSV 输出出现错误

python - 我无法在 python 上导入漂亮的汤

python - 如何在 Django QuerySet 中使用 Python 类型提示?

python - Pyinstaller ld-linux-x86-64.so.2 链接问题

python - 计算图像中白色像素的总数

excel - 在 Excel 中保存为 CSV 会丢失区域日期格式