簡體   English   中英

將循環函數輸出存儲到列表中

[英]Storing Loop Function Outputs into a List

輸入

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]

我嘗試創建一個空列表然后附加它,但我似乎無法弄清楚如何讓它輸出我上面顯示的所需列表。 有小費嗎?

這是我正在使用的數據類

@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
[match_exp_at_year(ModelInputs, year) if year < data.n_machines else 0 for year in range(data.max_year)]

無法重現您的輸出,但一般而言,下面是將值附加到 Python 的 for 循環中的列表的示例:

my_list = []
for i in range(0,100):
    my_list.append(i)

就在你的第一個循環之上,聲明並初始化一個空列表:

myList = []

緊接在您的第一個打印語句下(並在循環中)添加以下行:

myList.append(mach_exp_t)

然后在您的第二個打印語句下(並在循環中):

myList.append(0)

在最底部打印結果:

print ( myList )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM