TheEmperor
TheEmperor

Reputation: 355

How to multiply python string and integer 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.

Upvotes: 3

Views: 4563

Answers (6)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

[elem+a[count] for count,elem in enumerate(b)]

Try this with enumerate

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19264

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.

Upvotes: 2

Dima Tisnek
Dima Tisnek

Reputation: 11779

["".join(x) for x in zip(a, map(str, b))]
['A2', 'B50', 'C99']

or perhaps simpler:

["%s%s" % x for x in zip(a, b)]

assumin that OP had mising quotes in desired output

Upvotes: 0

d-coder
d-coder

Reputation: 13993

You can't multiply a string and int values. You have to convert both into string format and then concatenateit. I executed the following code which actually outputs as you asked for.Hope it helps. Not surely the best way but definitely one of the ways to do it.

a = ['A', 'B', 'C']

b = [2, 10, 120]
ab=[]
for i in range(len(a)):
    ab.append(a[i]+str(b[i]))
print ab

this is the output :

['A2', 'B10', 'C120']

Upvotes: 1

kumar
kumar

Reputation: 2620

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']

Upvotes: 4

Richard
Richard

Reputation: 217

Although zip() is the preferred solution, I believe the original problems with the way you were doing it were:

  1. You were not converting the integers to strings (solved in To Click's answer)

  2. You were not adding the strings (still incorrect in To Click's answer)

There could be a problem if the arrays are of different sizes, a problem taken care of by zip().

Upvotes: 1

Related Questions