【发布时间】:2019-10-24 06:36:24
【问题描述】:
我正在使用numpy 生成一个二维数组,但在尝试使用特定索引访问时出错。
MaxIt=100
PopSize = 30
w=1
c1=2
c2=2
#Intialisation
empty_particle = {'position': None,
'velocity': None,
'cost': None,
'best_position': None,
'best_cost': None}
gbest = {'position': None, 'cost': np.inf}
# Create Initial Population
pop = [];
for i in range(0, PopSize):
pop.append(empty_particle.copy())
pop[i]['position'] = np.random.uniform(VarMin, VarMax, nVar)
pop[i]['velocity'] = np.zeros(nVar)
pop[i]['cost'] = CostFunction(pop[i]['position'])
pop[i]['best_position'] = pop[i]['position'].copy()
pop[i]['best_cost'] = pop[i]['cost']
if pop[i]['best_cost'] < gbest['cost']:
gbest['position'] = pop[i]['best_position'].copy()
gbest['cost'] = pop[i]['best_cost']
pop[2]['position']
最后一行显示错误。我只想打印列表中的第二个元素pop,即pop[2]
【问题讨论】:
-
请添加 MRE stackoverflow.com/help/minimal-reproducible-example 和错误。
-
pop开始为空。您添加一个元素,并使用pop[0]设置值。但是然后尝试对pop[2]做一些事情,当元素的数量只有 1 个时!