Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform a temporary assignment in a generator expression? [duplicate]

I'm using a generator expression to find the index of keywords in a long string read from a file but only paying attention to keys that occur after a specific index I've already found.

end = min([fileStr.find(key) for key in keys if fileStr.find(key) > index])

It seems a little unnecessary and messy looking to have the find function repeated twice, could the result of the first find be somehow referenced again for the if expression at the end?

I checked if regular assignment would, and it produced syntax errors as I expected.

end = min([fileStr.find(key)=result for key in keys if result > index])
SyntaxError: invalid syntax
end = min([(fileStr.find(key)=result) for key in keys if result > index])
SyntaxError: invalid syntax
end = min([(result=fileStr.find(key)) for key in keys if result > index])
SyntaxError: invalid syntax
like image 322
SuperBiasedMan Avatar asked Dec 06 '25 02:12

SuperBiasedMan


1 Answers

You could nest generators...

end = min(x for x in (fileStr.find(key) for key in keys)
          if x > index)
like image 188
6502 Avatar answered Dec 08 '25 14:12

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!