Jorge Reyes
Jorge Reyes

Reputation: 3

How do I fill an empty list in a for loop?

I was trying to do this in code, it's like filling an empty list with more lists.

#These are the components I'm gonna use. I'm not using all of them.
     nc3=[-970689, 7.151, -.7698, 13.7097, 1872.82, -25.1011]
     ic4=[-1166846, 7.727, -0.9221, 13.8137, 2150.23, -27.6228]
     nc4=[-1280557, 7.95, -0.9646, 13.9836, 2292.44, -27.8623]
     ic5=[-1481583, 7.581, -0.9316, 13.6106, 2345.09, -40.2128]
     nc5=[-1524891, 7.331, -0.8914, 13.9778, 2554.6, -36.2529]
     nc6=[-1778901, 6.968, -0.8463, 14.0568, 2825.42, -42.7089]
     nc7=[-2013803, 6.529, -0.7954, 13.9008, 2932.72, -55.6356]
     nc9=[-255104, 5.693, -0.6782, 13.9548, 3290.56, -71.5056]

components=input("How many components are you gonna use? ")

g=[]
for i in range (components):

But I'm stuck there. How do I fill g without typing so much code?

There can be the case where I use 4 components, but they can be different. How can I do something more general? Is for the correct command or do I need to do it in a while loop?

Upvotes: 0

Views: 630

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27191

From what I understand, you want to select a range of components.

As always when trying to write generic code, put them inside a data structure. I suggest a list:

choices = [nc3, ic4, nc4, ic5, nc5, nc6, nc7, nc9]

Now the problem becomes very simple:

n = input("How many components are you gonna use? ")
components = choices[0:n]

If instead you wish to select which components to use by index:

chosen = input("Which components are you gonna use? ")
idxs = [int(x) for x in chosen.split(' ')]
components = [x for i, x in enumerate(choices) if i in idxs]

If instead you wish to select which components to use by name:

choices = [
    'nc3': nc3, 'ic4': ic4, 'nc4': nc4,
    'ic5': ic5, 'nc5': nc5, 'nc6': nc6,
    'nc7': nc7, 'nc9': nc9]

chosen = input("Which components are you gonna use? ")
names = [x for x in chosen.split(' ')]
components = [choices[x] for x in names]

Upvotes: 3

Related Questions