r/learnpython • u/lehmagavan • Sep 26 '26
Parsing large collections of "numeric" strings.
Hi, I'm just a hobbyist and I'm not very familiar with Python ecosystem. I recently came across a specific problem:
I have an iterable (or yield via generator) that contains millions of floating point values, but each one is a Python str, made up example: ["1.987", "0.037389", "1.2", ...]
What's the most efficient way to aggregate them and calculate say, the mean?
I'm writing my own C extension for this and would like to know what to benchmark it against. Couldn't find information on any std way that would avoid calling the float() constructor on each string.
View all comments
Show parent comment
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 27 '26
I just did my own testing, and on average using a list is slightly faster, as I would've expected.
That being said, personally I much prefer memory savings over runtime performance, especially in cases where the difference is minuscule, so I would still use
np.fromiterunless I had a reason not to.gen_stringsreturns a generator, which is a subclass of iterator. Just in case that wasn't obvious. I made the function to make use ofipython's%timeitmagic function which tests things several times to get a better average result. If I'd left that out, after the first run the iterator would've been empty.