I have a function
def f():
# whatever
yield (a,b)
Now I would like to collect all the a
but not b
. Also I want the result aa
to be a list instead of iterator. Right now I use
aa, _ = zip(*f())
Is this the best one can do in terms of space/time efficiency?
zip(*seq)
has to ingest the whole generator, before it can output the columns. This is not efficient.
Just stick to a list comprehension. You could use tuple assignment:
aa = [a for a, _ in f()]
or use indexing:
aa = [tup[0] for tup in f()]
If you don't have to have all values available for random access or other operations that must have a list, you can use a generator expression to maintain the memory efficiency:
aa = (a for a, _ in f())
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