Python如何返回索引和值

时间:2017-11-21 10:11:40

标签: python python-3.x python-2.7

a = [1,2,2,3,1,4,2]

在Matlab中我可以找到索引和值如下:

[val, idx] = find(a>=2);

输出将是

val = [2,2,4,2]
idx = [2,3,6,7]

在Python中执行此操作的最简单方法是什么?

2 个答案:

答案 0 :(得分:3)

EDIT:由于您修改了问题,因此这里是更新后的答案

>>> index, values = zip(*[(index, data) for index, data in enumerate(a) if data >= 2 ])
>>> values
(2, 2, 3, 4, 2)
>>> index
(1, 2, 3, 5, 6)

您只需使用list comprehension即可获得所有索引发生次数

>>> a = [1,2,2,3,1,4,2]
>>> val = 2
>>> [index for index, data in enumerate(a) if data == val ]
[1, 2, 6]

但是如果你想保持价值,你也可以把它作为元组来挖掘:

>>> index, val = [ index for index, data in enumerate(a) if data == val ], val
>>> index, val
([1, 2, 6], 2)

答案 1 :(得分:2)

最简单的方法,因为你要与matlab进行比较,你可以使用numpy

import numpy as np

a = np.array([1,2,2,3,1,4,2])
a >= 2  # Just to check what you get by doing this boolean operation
values = a[a>=2]  # using the conditional to filter a numpy array
indeces = np.argwhere(a>=2).reshape(-1)  # to get the indices