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
You could nest generators...
end = min(x for x in (fileStr.find(key) for key in keys)
if x > index)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With