【问题标题】:How to insert a row and a column in a recursive table如何在递归表中插入一行和一列
【发布时间】:2016-03-04 17:28:57
【问题描述】:

我发布这个问题是因为我一遍又一遍地尝试没有结果。 我编写了一个表格,在 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,还是可以随手创建?

标签: python python-2.7 export-to-csv


【解决方案1】:

随着您的进展生成文件的解决方案,而不是尝试生成包含所有列表的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)])

【讨论】:

    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多