可能重复:
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']
可能重复:
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']
>>> 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']
>>> 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']
+1这是一个更好的解决方案,因为产品将比嵌套循环更高效,并且更灵活。 – 2012-04-23 16:24:56
使用c = ["%d%s" % (x,y) for x in a for y in b]
列表理解可以遍历多个对象。
In[3]: [str(a1)+b1 for a1 in a for b1 in b]
Out[3]: ['1a', '1b', '2a', '2b', '3a', '3b']
请注意将数字转换为字符串的细微之处。
只需使用“嵌套”版本。
c = [str(i) + j for i in a for j in b]
import itertools
c=[str(r)+s for r,s in itertools.product(a,b)]
有点类似版本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']
可能重复[获取Python中的一系列列表的笛卡儿积(http://stackoverflow.com/questions/ 533905 /获得笛卡尔产品的一系列列表在蟒蛇)(也见http://stackoverflow.com/questions/4481724/python-convert-list-of-char-into -串)。 – 2012-04-23 14:54:30