如何通过Python查找数组中元素的位置?

如何通过Python查找数组中元素的位置?,python,arrays,python-3.x,numpy,Python,Arrays,Python 3.x,Numpy,我有以下数组: scores=[2.619,3.3, 9.67, 0.1, 6.7,3.2] 我希望通过以下代码检索超过5个的元素: min_score_thresh=5 Result=scores[scores>min_score_thresh] 因此,这将导致以下结果: [9.67, 6.7] 现在我希望得到这两个元素的位置,这是我期望的答案,将存储在变量x中: x=[2,4] 请与我分享想法,谢谢使用numpy。其中提供矢量化解决方案: def find_scores(a_li

我有以下数组:

scores=[2.619,3.3, 9.67, 0.1, 6.7,3.2]
我希望通过以下代码检索超过5个的元素:

min_score_thresh=5
Result=scores[scores>min_score_thresh]
因此,这将导致以下结果:

[9.67, 6.7]
现在我希望得到这两个元素的位置,这是我期望的答案,将存储在变量x中:

x=[2,4]


请与我分享想法,谢谢使用
numpy。其中
提供矢量化解决方案:

def find_scores(a_list, min):
    filters = list(filter( lambda x: x[1]> min, [(i[0],i[1]) for i in enumerate(a_list) ]))
    return [i[0] for i in filters]
import numpy as np

scores = np.array([2.619,3.3, 9.67, 0.1, 6.7,3.2])
min_score_thresh = 5

res = np.where(scores>min_score_thresh)[0]

print(res)

[2 4]
通过列表理解获取索引(或值)很容易:

In [33]: [i for i,v in enumerate(scores) if v>5]
Out[33]: [2, 4]
我们可以将两者都作为元组列表获得,其中包括:

In [34]: [(i,v) for i,v in enumerate(scores) if v>5]
Out[34]: [(2, 9.67), (4, 6.7)]
然后我们可以使用
zip*
习惯用法来“转置”此列表:

In [35]: list(zip(*_))
Out[35]: [(2, 4), (9.67, 6.7)]
或者使用解包将所有表达式包装到一个表达式中:

In [36]: v,x = tuple(zip(*((i,v) for i,v in enumerate(scores) if v>5)))
In [37]: v
Out[37]: (2, 4)
In [38]: x
Out[38]: (9.67, 6.7)

乍一看,从列表理解中获得多个列表是一件棘手的事情,但这种zip*转换可以解决这一问题。

使用
numpy

x = np.flatnonzero(np.greater(scores, min_score_thresh)).tolist()
注意:
.tolist()
如果您可以使用
numpy.ndarray
s.

简单的OneLiner,则不需要使用
.tolist()

scores = [2.619, 3.3, 9.67, 0.1, 6.7, 3.2]
min_score_thresh = 5

result = [scr for scr in scores if scr > min_score_thresh]
index_ = [scores.index(x) for x in result]
使用字典

scores = [2.619,3.3, 9.67, 0.1, 6.7,3.2]
min_score_thresh = 5


index_dict = {}
 
for index, word in enumerate(scores):
    if word > min_score_thresh :
        index_dict.setdefault(word, index)
 

print(*index_dict.values()) 
给予

scores = [2.619,3.3, 9.67, 0.1, 6.7,3.2]
min_score_thresh = 5


index_dict = {}
 
for index, word in enumerate(scores):
    if word > min_score_thresh :
        index_dict.setdefault(word, index)
 

print(*index_dict.values()) 
2 4

[Program finished]