I have two different lists which I would like to combine
a = ['A', 'B', 'C']
b = [2, 10, 120]
So the desired output should be like this:
ab = ['A2', 'B10', 'C120']
I've tried this:
ab = [a[i]*b[i] for i in range(len(a))]
But I now understand that this will only work if I want to multiply two array of integers. So what should I do in order to get the desired output as above?
Thank you.
The same idea as To Click's, but a little different, you can type cast after unpacking the items
>>> [str(y)+str(x) for y,x in zip(a, b)]
['A2', 'B10', 'C120']
You could use zip() to do this:
>>> zip(a, [str(i) for i in b])
[('A', '2'), ('B', '10'), ('C', '120')]
As such:
>>> a = ['A', 'B', 'C']
>>>
>>> b = [2, 10, 120]
>>> [y + z for (y, z) in zip(a, [str(i) for i in b])]
['A2', 'B10', 'C120']
>>>
In this example, we are first converting each integer in b to a string, so that we can do string concatenation, then we zip a and b together, so that we can easily loop over the new list using another list comprehension and string concatenation to get the desired result.
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