2012-04-23 71 views
2

可能重複:
Get the cartesian product of a series of lists in Python列表理解

有什麼辦法,我可以合併兩個列表A和B到使用Python列表內涵C,

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

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

可能重複[獲取Python中的一系列列表的笛卡兒積(http://stackoverflow.com/questions/ 533905 /獲得笛卡爾產品的一系列列表在蟒蛇)(也見http://stackoverflow.com/questions/4481724/python-convert-list-of-char-into -串)。 – 2012-04-23 14:54:30

回答

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

有了新的字符串格式化

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

+1這是一個更好的解決方案,因爲產品將比嵌套循環更高效,並且更靈活。 – 2012-04-23 16:24:56

2

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

2

列表理解可以遍歷多個對象。

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

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

請注意將數字轉換爲字符串的細微之處。

2

只需使用「嵌套」版本。

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

有點類似版本jamylak的解決方案:的

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