4

I have following array:

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

And I wish to retrieve the elements which more than 5 by following code:

min_score_thresh=5
Result=scores[scores>min_score_thresh]

Hence this will result me result:

[9.67, 6.7]

Now i wish to get the positions of this two element which is my expected answer will be store in variable x:

x = [2,4]

Please share me ideas, thanks

7 Answers 7

5

Use numpy.where for a vectorised solution:

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]
Sign up to request clarification or add additional context in comments.

Comments

2
scores = [2.619, 3.3, 9.67, 0.1, 6.7, 3.2]

min_score_thresh = 5

# score is 5 or higher
result = []

# position in 'scores' list
indx = []

for i, item in enumerate(scores):
    if item > min_score_thresh:
        result.append(item)
        indx.append(i)

x = indx

print(result)
print(x)

Comments

2

Getting the indices (or values) via list comprehension is easy:

In [33]: [i for i,v in enumerate(scores) if v>5]
Out[33]: [2, 4]

We can get both, as a list of tuples with:

In [34]: [(i,v) for i,v in enumerate(scores) if v>5]
Out[34]: [(2, 9.67), (4, 6.7)]

Then we can use a zip* idiom to 'transpose' this list:

In [35]: list(zip(*_))
Out[35]: [(2, 4), (9.67, 6.7)]

Or wrapping that all in one expression with unpacking:

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)

At a first glance getting several lists from a list comprehension is tricky, but this zip* transposition takes care of that.

Comments

2

Using numpy:

x = np.flatnonzero(np.greater(scores, min_score_thresh)).tolist()

NOTE: .tolist() is not necessary if you can live with numpy.ndarrays.

Comments

1
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]

Comments

1

simple oneliners

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]

Comments

0

Using Dictionary,

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()) 

gives

2 4

[Program finished]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.