简体   繁体   中英

Storing Loop Function Outputs into a List

INPUT

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}.')

OUTPUT:

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.

Now I would like to create a list that stores these values. The list should read [1000000, 1000000, 1000000, 1000000, 1000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

I tried creating an empty list and then appending it, but I can't seem to figure out how to get it to output the desired list I showed above. Any tips?

HERES THE DATA CLASS I AM WORKING WITH

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

Can't reproduce your output, but in general below is an example of appending values to a list in Python's for loop:

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

Just above your first loop, declare and initialise an empty list:

myList = []

Immediately under your first print statement (and in the loop) add the line:

myList.append(mach_exp_t)

and then under your second print statement (and in the loop):

myList.append(0)

Print the result right at the very bottom with:

print ( myList )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM