2

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'] 
Cœur
  • 34,719
  • 24
  • 185
  • 251
Sudhagar Sachin
  • 545
  • 2
  • 6
  • 14
  • 4
    possible duplicate of [Get the cartesian product of a series of lists in Python](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) (also see http://stackoverflow.com/questions/4481724/python-convert-list-of-char-into-string). – Felix Kling Apr 23 '12 at 14:54

7 Answers7

6
>>> 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']
jamylak
  • 120,885
  • 29
  • 225
  • 225
6
>>> 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']
Maehler
  • 5,841
  • 1
  • 38
  • 45
2

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

gefei
  • 18,124
  • 7
  • 49
  • 65
2

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.

Andrew Jaffe
  • 25,476
  • 4
  • 47
  • 58
2

Just use the "nested" version.

c = [str(i) + j for i in a for j in b]
Xion
  • 21,580
  • 9
  • 51
  • 77
2
import itertools
c=[str(r)+s for r,s in itertools.product(a,b)]
mkurmag
  • 21
  • 3
1

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']
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487