如何在for循环中填充空列表?

时间:2018-03-13 05:04:51

标签: python list

我试图在代码中执行此操作,这就像填充包含更多列表的空列表一样。

#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):

但我被困在那里。如何在不输入如此多代码的情况下填写g?

可能存在我使用4个组件的情况,但它们可能不同。我怎样才能做更多一般的事情?是为了正确的命令还是我需要在while循环中执行它?

1 个答案:

答案 0 :(得分:3)

据我了解,您想要选择一系列组件。

与尝试编写通用代码时一样,将它们放在数据结构中。我建议一个清单:

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

现在问题变得非常简单了:

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

如果您希望选择哪些组件按索引使用

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]

如果您希望选择哪些组件按名称使用

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]