N08
N08

Reputation: 1315

Applying if-else one-liner on lists in Python

I have an array y that takes a value of either 0 or 1. Then I have an array yp that takes values between 0 and 1. The two arrays have the same length.

If an entry in y is 1, then I want to append the corresponding yp to a list, otherwise I want to append 1-yp:

y  = [1,1,1,0,0]
yp = [0.1, 0.2, 0.3, 0.4, 0.5]

x = []
for idx, i in enumerate(y):
    if i:
        x.append(yp[idx])
    else:
        x.append(1-yp[idx])

Is there a shorter way to write this in Python, perhaps without a for-loop?

Upvotes: 0

Views: 75

Answers (4)

ldavid
ldavid

Reputation: 2552

If your lists are very long, there's a more efficient way using numpy:

y, yp = map(np.asarray, (y, yp)  # convert to an array
x = y * yp + (1 - y) * (1 - yp)

The code above, explained:

  • a = y * yp: results in an array with the same length as y (and yp) with 1 * yp where y = 1 and 0 where y = 0.
  • b = (1 - y) * (1 - yp): results in an array with 1-yp where y=0 and 0 where y = 1.
  • a + b is the pairwise sum and yields your expected result.

Upvotes: 2

bla
bla

Reputation: 1870

You can use a list comprehension with zip to iterate over both lists simultaneously:

>>> y  = [1,1,1,0,0]
>>> yp = [0.1, 0.2, 0.3, 0.4, 0.5]
>>> [b if a else 1 - b for a, b in zip(y, yp)]
[0.1, 0.2, 0.3, 0.6, 0.5]

Upvotes: 3

Dadep
Dadep

Reputation: 2788

You are asking for list comprehension (what you call "one-liner" ??) such as :

y  = [1,1,1,0,0]
yp = [0.1, 0.2, 0.3, 0.4, 0.5]
l=[yp[i] if y[i]==1 else 1-yp[i] for i in range(len(y))]

whill give you :

>>> l
[0.1, 0.2, 0.3, 0.6, 0.5]

Upvotes: 1

Ankur Sinha
Ankur Sinha

Reputation: 6639

Perhaps you are looking for something like this if I understand you correctly?

for idx, i in enumerate(y):
    x.append(yp[idx]) if i else x.append(1-yp[idx])

More like a ternary operation approach?

Reference: http://book.pythontips.com/en/latest/ternary_operators.html

Upvotes: 2

Related Questions