1

I have an iterator result in one function and I need to return an iterator after making some changes to the objects in result from that function. I don't want to iterate over the result as it is causing performance degradation. I want to perform that operation on the fly for each item in the result.

This is the code which iterates over the result to do that operation.

sols = []
# Get rid of this loop
for sol in result:
    sols.append(dict((symbols[abs(lit) - 1], lit > 0) for lit in sol))
# Return iterator object
return (sol for sol in sols)
Sudhanshu Mishra
  • 2,024
  • 1
  • 22
  • 40

1 Answers1

2

You're almost there. Just don't store the values in a sols list:

def f(result):
  return (dict((symbols[abs(lit) - 1], lit > 0) for lit in sol) for sol in result)

This yields (no pun intended) a generator which incrementally traverses the given result parameter.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207