1

I have an array of non-unique numbers (x) and another array of the same length with some values (y). I would like to return an array (z) which is the same length as x but only shows the unique values of x when y is a maximum. E.g.

x = [0, 2, 2, 2, 0, 3, 3]
y = [1, 1, 1.5, 1, 1, 1.5, 1]
z = [0, 0, 2, 0, 0, 3, 0]

Does anyone please know how I can get the array z?

1 Answer 1

3

You could use a list comprehension and zip:

x = [0, 2, 2, 2, 0, 3, 3]
y = [1, 1, 1.5, 1, 1, 1.5, 1]

my = max(y)

z = [xi if my == yi else 0 for xi, yi in zip(x, y)]
print(z)

Output

[0, 0, 2, 0, 0, 3, 0]

The above list comprehension is equivalent to the following for loop:

z = []
for xi, yi in zip(x, y):
    if yi == my:
        z.append(xi)
    else:
        z.append(0)
Sign up to request clarification or add additional context in comments.

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.