Python将范围值导出到cs

2024-04-26 22:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

当前将范围值打印到终端。我需要将这些值导出到csv文件。”print S[t-1],I[t-1],R[t-1]“是值。。。你知道吗

import matplotlib.pyplot as plt
import numpy
beta = 0.24
gamma = 0.142857
Tstart = 0
Tend = 151
r = 0
s = (306.8 * 10**6)
i = (22 * 10**6)

def compute_next_day(t,R,I,S):
    R[t] = gamma * I[t - 1] + R[t - 1]
    I[t] = (beta * I[t-1] * S[t-1] / (r+i+s)) - gamma * I[t-1] + I[t-1]
    S[t] = - (beta * I[t-1] * S[t-1] / (r+i+s)) + S[t-1]
    print S[t-1], I[t-1], R[t-1]


def compute_entire_period(Tstart, Tend, R, I, S):
    R[Tstart] = r
    I[Tstart] = i
    S[Tstart] = s
    for t in range(Tstart + 1, Tend):
        compute_next_day(t, R, I, S)


R = range(Tstart, Tend)
I = range(Tstart, Tend)
S = range(Tstart, Tend)

Tags: 文件csvimport终端matplotlibdefrangebeta
2条回答

这样的方法应该有用:

def compute_next_day(t,R,I,S,):
    ...
    return S[t-1], I[t-1], R[t-1] # return values instead of printing to terminal

with open('path_to_file.csv','w') as f:
    for ... : # your choice of loop
        vals = compute_next_day(...) # compute your values
        f.write(','.join(vals) + '\n') # dump your values separated with ','

如果要将数据保存在CSV中,请使用dsv库:

import csv

beta = 0.24
gamma = 0.142857
Tstart = 0
Tend = 151
r = 0
s = (306.8 * 10 ** 6)
i = (22 * 10 ** 6)


def compute_next_day(t, R, I, S):
    R[t] = gamma * I[t - 1] + R[t - 1]
    I[t] = (beta * I[t - 1] * S[t - 1] / (r + i + s)) - gamma * I[t - 1] + I[t - 1]
    S[t] = - (beta * I[t - 1] * S[t - 1] / (r + i + s)) + S[t - 1]
    return [S[t-1], I[t-1], R[t-1]]


def compute_entire_period(Tstart, Tend, R, I, S):
    R[Tstart] = r
    I[Tstart] = i
    S[Tstart] = s
    with open('mydata.csv', 'w') as mycsvfile:
        writer = csv.writer(mycsvfile)
        for t in range(Tstart + 1, Tend):
            writer.writerow(compute_next_day(t, R, I, S))


R = range(Tstart, Tend)
I = range(Tstart, Tend)
S = range(Tstart, Tend)

compute_entire_period(Tstart, Tend, R, I, S)

相关问题 更多 >