user1821176
user1821176

Reputation: 1191

How to create a new array based on a condition from 2 arrays?

I have two corresponding arrays

x = ['30', '67', '25.6', '15', '23', '78']
y = ['success', 'fail', 'success', 'live', 'fail', 'success']

I'm trying to create an if statement or definition to change the x array for satisfying the y array of the condition 'success' such that my new x array would be

new_x = ['30', '25.6', '78']

Upvotes: 1

Views: 290

Answers (2)

U13-Forward
U13-Forward

Reputation: 71570

Try this:

print([a for a,b in zip(x,y) if b == 'success'])

Upvotes: 2

John Gordon
John Gordon

Reputation: 33310

You can use enumerate() to loop over the values in a collection and also keep track of the current position.

x = ['30', '67', '25.6', '15', '23', '78']
y = ['success', 'fail', 'success', 'live', 'fail', 'success']

new_x = []

for position, word in enumerate(y):
    if word == 'success':
        new_x.append(x[position])

Upvotes: 0

Related Questions