I am looking for the shortest way of doing the following (one line solution)
a = ["a", "b", "c"]
b = ["w", "e", "r"]
I want the following output:
q = ["a w", "b e", "c r"]
Of course this can be achieved by applying a for loop. But I am wondering if there is a smart solution to this?
You can use str.join()
and zip()
, Example -
q = [' '.join(x) for x in zip(a,b)]
Example/Demo -
>>> a = ["a", "b", "c"]
>>> b = ["w", "e", "r"]
>>> q = [' '.join(x) for x in zip(a,b)]
>>> q
['a w', 'b e', 'c r']
You can use zip
within a list comprehension :
>>> ['{} {}'.format(*i) for i in zip(a,b)]
['a w', 'b e', 'c r']
More pythonic way;
b = map(' '.join,zip(a,b))
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