2

I have an array of numbers:

a=  [[0, 0.1667],
 [1, 0.1667],
 [2, 0.25], 
 [3, 0.25],
 [4, 0.167]].

Each pair contains numbers and their proportions.

I want to compare a particular number Z with the resulted proportions. Lets assume, Z=0.02. So I have to iterate through the proportions and compare each proportion with Z and find the number whose proportion falls below Z and print that number only.

I think, the proportions need to sorted from highest to lowest first and then it has be compared with Z.

0

2 Answers 2

1

Sorting will be helpful if you're dealing with lots of data, then you can just loop until the first element is bigger than z and you're done.

However, an easy way for going through all elements would be using a list comprehension:

a = [[0, 0.1667],
 [1, 0.1667],
 [2, 0.25], 
 [3, 0.25],
 [4, 0.167]]

z = 0.2
print [x for x in a if x[1] < z]

This will iterate through all elements in a and check if the second number of each element in a is less than z, if yes, they get added to the new list.

Output:

>>> 
[[0, 0.1667], [1, 0.1667], [4, 0.167]]

(I chose z = 0.2, because with z = 0.02 the list is empty :) )

Sign up to request clarification or add additional context in comments.

Comments

0

If you have to work with a single such array with multiple values of Z, then sorting will be helpful. Otherwise simply loop over the array and compare proportions with Z and create your desired list. Sorting the array in this case would be more expensive.

PS: If your question is how to sort the array according to proportions:

a.sort(key=lambda x: x[1]))

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.