-1

In R there is function ifelse(test_expression, x, y), does Python have smth like this?

Artem T
  • 27
  • 3
  • Why ask a question and then immediately answer it? – neuron Nov 21 '21 at 22:03
  • 1
    @neuron if you figure out something that might be useful to other people, it is a useful way to record and share that information. In this case the question happens to be a duplicate, so it should get flagged as such and closed. – shadowtalker Nov 21 '21 at 22:38

2 Answers2

1

With help from this answer about a ternary form of if:

def ifelse(t, x, y):
   return list(map(lambda t, x, y: x if t else y, t, x, y ))

I don't do much Python so this may be sub-optimal/non-pythonic ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
0

Indeed there is at least one such function from numpy:

import numpy as np
np.where(list > 0.8, 1, 0)

For example for changing list's elements based of logical expression.

martineau
  • 119,623
  • 25
  • 170
  • 301
Artem T
  • 27
  • 3