Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply python string and integer arrays

Tags:

python

arrays

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.

like image 338
TheEmperor Avatar asked Aug 31 '26 07:08

TheEmperor


2 Answers

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']
like image 82
kumar Avatar answered Sep 02 '26 10:09

kumar


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.

like image 26
A.J. Uppal Avatar answered Sep 02 '26 09:09

A.J. Uppal