错误'不在列表中'

时间:2016-08-22 15:09:53

标签: python list

我正在尝试获取outputx [vX]

中值的索引值
>>> outs = np.array(outputx[vX]).tolist()
>>> print outs
[0.806, 0.760, 0.8]
>>> print type(outs)
(type 'list')
>>> idx = outputX.index(outs)
error -> [0.806, 0.760, 0.8] is not in list

这是什么意思,我做错了什么?

2 个答案:

答案 0 :(得分:0)

index list方法需要一个值,并在调用该方法的列表中返回该值的位置。如果给定值不在列表中,则该方法将引发ValueError异常。所以,例如:

>>> [2, 4, 6, 8].index(6)
2
>>> [2, 4, 6, 8].index("no such value")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'no such value' is not in list

您的代码中出现错误,因为outputX中没有元素(应该是outputx,就像Python区分大小写的那样)包含列表[0.806, 0.760, 0.8]

原因是您正在比较不同类型的数据。从问题中可以清楚地看出你期望发生什么。

答案 1 :(得分:0)

如果您需要索引列表,可以使用列表推导:

idx = [outputX.index(i) for i in outs]

但你应该确定outs列表的所有值都在outputX列表中,否则python会给你一个ValueError