将循环函数输出存储到列表中

2024-09-24 16:29:40 发布

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

输入

def mach_exp_at_year(data: ModelInputs, year):
    mach_exp_t = data.cost_machine_adv
    return mach_exp_t

for i in range(data.n_machines):
    year = i + 1
    mach_exp_t = mach_exp_at_year(ModelInputs, year)
    print(f'The machine expense at year {year} is ${mach_exp_t:,.0f}.')

for i in range(data.n_machines, data.max_year):
    year = i + 1
    print(f'The machine expense at year {year} is ${0:,.0f}.')

输出:

The machine expense at year 1 is $1,000,000.
The machine expense at year 2 is $1,000,000.
The machine expense at year 3 is $1,000,000.
The machine expense at year 4 is $1,000,000.
The machine expense at year 5 is $1,000,000.
The machine expense at year 6 is $0.
The machine expense at year 7 is $0.
The machine expense at year 8 is $0.
The machine expense at year 9 is $0.
The machine expense at year 10 is $0.
The machine expense at year 11 is $0.
The machine expense at year 12 is $0.
The machine expense at year 13 is $0.
The machine expense at year 14 is $0.
The machine expense at year 15 is $0.
The machine expense at year 16 is $0.
The machine expense at year 17 is $0.
The machine expense at year 18 is $0.
The machine expense at year 19 is $0.
The machine expense at year 20 is $0.

现在我想创建一个存储这些值的列表。列表应为[1000000,1000000,1000000,1000000,1000000,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

我尝试创建一个空列表,然后添加它,但我似乎不知道如何让它输出上面显示的所需列表。有什么建议吗

这是我正在使用的数据类

@dataclass
class ModelInputs:
    n_phones: float = 100000
    price_scrap: float = 50000
    price_phone: float = 2000
    cost_machine_adv: float = 1000000
    cogs_phone: float = 250
    n_life: int = 10
    n_machines: int = 5
    d_1: float = 100000
    g_d: float = 0.2
    max_year: float = 20
    interest: float = 0.05

    # Inputs for bonus problem
    elasticity: float = 100
    demand_constant: float = 300000

data = ModelInputs()
data

Tags: the列表fordataismachinefloatyear
3条回答

在第一个循环的正上方,声明并初始化一个空列表:

myList = []

在第一个打印语句(以及循环中)的下面添加以下行:

myList.append(mach_exp_t)

然后在第二个打印语句下(在循环中):

myList.append(0)

在最底部打印结果,并使用:

print ( myList )

无法重现您的输出,但通常以下是在Python for循环中将值附加到列表的示例:

my_list = []
for i in range(0,100):
    my_list.append(i)
[match_exp_at_year(ModelInputs, year) if year < data.n_machines else 0 for year in range(data.max_year)]

相关问题 更多 >