0

I have the following code:

[mc.split('$', 1)[-1] for mc in marketCapsUnclean if 'B' in mc]

Which transforms something like:

['blabla $10M', 'blabla $10B']

into

['$10B']

I would like instead to get a value for the elements which don't pass the if test, like this:

['N/A', '$10B']

I would like to do something like:

[mc.split('$', 1)[-1] for mc in marketCapsUnclean if 'B' in mc else 'N/A']

But this is not legal syntax.

So is there a way to achieve something similar with a for comprehension?

bsky
  • 19,326
  • 49
  • 155
  • 270
  • No, because the `if` is a *filter*. Include this item or don't include it, a boolean choice. – Martijn Pieters Jan 27 '18 at 18:57
  • You are not filtering. You are producing different values for each item, so you want to use a *conditional expression* in the value expression. `[mc.split('$', 1)[-1] if 'B' in mc else 'N/A' for mc in marketCapsUnclean]`. See the duplicate. – Martijn Pieters Jan 27 '18 at 18:59

1 Answers1

5

Add the else condition with value after the if before the looping structure:

[mc.split('$', 1)[-1] if 'B' in mc else 'N/A' for mc in marketCapsUnclean ]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102