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
  • 37,241
  • 25
  • 195
  • 267
Sudhagar Sachin
  • 565
  • 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
  • 128,818
  • 30
  • 231
  • 230
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
  • 6,111
  • 1
  • 41
  • 46
2

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

gefei
  • 18,922
  • 9
  • 50
  • 67
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
  • 26,554
  • 4
  • 50
  • 59
2

Just use the "nested" version.

c = [str(i) + j for i in a for j in b]
Xion
  • 22,400
  • 10
  • 55
  • 79
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
  • 244,495
  • 58
  • 464
  • 504