The function foo below takes in a number and returns a tuple of strings. Can I write the following loop as a one-liner?
r1 = []
r2 = []
for i in range(10):
(s1, s2) = foo(i)
r1.append(s1)
r2.append(s2)
# r1 now has the first returned strings from each iteration of the loop, and similarly for r2
You just need to do this simple
r1, r2 = map(list, zip(*foo))
I would do something like this:
def foo(i):
return (i,i+1)
r1, r2 = [tpl for tpl in zip(*map(foo,range(10)))]
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