1

I have a reduce function that looks like this:

reduce(lambda x, y: x + y, [foo(x) for x in listValue], [])

I also have another function called goo and I want to use it when x achieves some condition, for example x >= 10 inside the reduce .

My idea is something like:

reduce(lambda x, y: x + y, [foo(x) for x in listValue if x < 10 else goo(x)], [])

but that gives me an error:

  File "<stdin>", line 1
    reduce(lambda x, y: x + y, [foo(x) for x in listValue if x < 10 else goo(x)], [])
                                                                       ^
SyntaxError: invalid syntax

How to solve this?

grooveplex
  • 2,492
  • 4
  • 28
  • 30
Phạm Trí
  • 61
  • 1
  • 1
  • 4

1 Answers1

1

for and if are in the wrong order. You first need to specify the if, then the for.

Use this reduce in your code:

reduce(lambda x, y: x + y, [(foo(x) if x < 10 else goo(x)) for x in listValue], [])
grooveplex
  • 2,492
  • 4
  • 28
  • 30
Hameda169
  • 608
  • 3
  • 9