Reputation: 565
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
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
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
Reputation: 22770
Just use the "nested" version.
c = [str(i) + j for i in a for j in b]
Upvotes: 2
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
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