Sudhagar Sachin
Sudhagar Sachin

Reputation: 565

List comprehensions in python

Is there any way I can combine two list a and b into c using list comprehensions in python,

a=[1,2,3]
b=['a','b']

c=['1a','1b','2a','2b','3a','3b'] 

Upvotes: 2

Views: 524

Answers (7)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

somewhat similar version of jamylak's solution:

>>> import itertools
>>> a=[1,2,3]
>>> b=['a','b']
>>>[str(x[0])+x[1] for x in itertools.product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

Upvotes: 1

jamylak
jamylak

Reputation: 133504

>>> from itertools import product
>>> a=[1,2,3]
>>> b=['a','b']
>>> ['%d%s' % el for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

With new string formatting

>>> ['{0}{1}'.format(*el) for el in product(a,b)]
['1a', '1b', '2a', '2b', '3a', '3b']

Upvotes: 6

mkurmag
mkurmag

Reputation: 21

import itertools
c=[str(r)+s for r,s in itertools.product(a,b)]

Upvotes: 2

Xion
Xion

Reputation: 22770

Just use the "nested" version.

c = [str(i) + j for i in a for j in b]

Upvotes: 2

Andrew Jaffe
Andrew Jaffe

Reputation: 27077

List comprehensions can loop over multiple objects.

In[3]: [str(a1)+b1 for a1 in a for b1 in b]

Out[3]: ['1a', '1b', '2a', '2b', '3a', '3b']

Note the slight subtlety of converting the number into a string.

Upvotes: 2

Maehler
Maehler

Reputation: 6331

>>> a = [1,2,3]
>>> b = ['a', 'b']
>>> c = ['%d%c' % (x, y) for x in a for y in b]
>>> c
['1a', '1b', '2a', '2b', '3a', '3b']

Upvotes: 6

gefei
gefei

Reputation: 19766

use c = ["%d%s" % (x,y) for x in a for y in b]

Upvotes: 2

Related Questions