知道如何在python中"TypeError: unsupported operand type(s) foR语言 : 'list' and 'list'"修复此错误吗?



我正在尝试为一个旅行推销员问题实现一个差分进化算法。我得到以下错误:"TypeError:不支持-:'list'和'list'的操作数类型"我知道我不能减去两个列表,但我不知道该怎么做才能解决这个问题。谢谢你的帮助。受影响的代码部分是:

x_1 = population[random_index[0]]
x_2 = population[random_index[1]]
x_3 = population[random_index[2]]
x_t = population[random_index[3]]
print("X_t", x_t)
# subtract x3 from x2, and create a new vector (x_diff)
x_diff = [x_2_i - x_3_i for x_2_i, x_3_i in zip(x_2, x_3)]
# multiply x_diff by the mutation factor (F) and add to x_1
v_donor = [x_1_i + mutate * x_diff_i for x_1_i, x_diff_i in zip(x_1, x_diff)]
v_donor = ensure_bounds(v_donor, bounds)

以下操作确实有效:

>>> x1 = [1,2,3,4,5]                                                                                          
>>> x2 = [2,2,2,2,2]                                                                                           
>>> print([x_1_i - x_2_i for x_1_i, x_2_i in zip(x1, x2)])
[-1, 0, 1, 2, 3]

也许你的输入不是标量?

最新更新