3

假设我有以下内容。

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]

如何获得以下内容?

[1,2,3,'a','b']
[1,2,3,'c','d']
[1,2,3,'e','f']
[4,5,6,'a','b']
[4,5,6,'c','d']
[4,5,6,'e','f']
[7,8,9,'a','b']
[7,8,9,'c','d']
[7,8,9,'e','f']
4

6 回答 6

11
from itertools import product
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]

print [x+y for (x,y) in product(a,b)]
于 2012-07-02T18:34:25.213 回答
4
In [1]: from itertools import product

In [2]: a = [[1,2,3],[4,5,6],[7,8,9]]

In [3]: b = [['a','b'],['c','d'],['e','f']]

In [4]: map(lambda x: x[0]+x[1], product(a, b))
Out[4]: 
[[1, 2, 3, 'a', 'b'],
 [1, 2, 3, 'c', 'd'],
 [1, 2, 3, 'e', 'f'],
 [4, 5, 6, 'a', 'b'],
 [4, 5, 6, 'c', 'd'],
 [4, 5, 6, 'e', 'f'],
 [7, 8, 9, 'a', 'b'],
 [7, 8, 9, 'c', 'd'],
 [7, 8, 9, 'e', 'f']]
于 2012-07-02T18:37:00.080 回答
2
>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = [['a','b'],['c','d'],['e','f']]
>>> [x+y for x in a for y in b]
[[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [1, 2, 3, 'e', 'f'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd'], [4, 5, 6, 'e', 'f'], [7, 8, 9, 'a', 'b'], [7, 8, 9, 'c', 'd'], [7, 8, 9, 'e', 'f']]
于 2012-07-02T18:36:48.420 回答
1
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
c = []
for x in a:
    for y in b:
        print x + y
        c.append(x + y)
于 2012-07-02T18:36:52.980 回答
1

只是为了好玩,因为玛丽亚的回答要好得多:

from itertools import product
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
print [sum(x, []) for x in product(a, b)]
于 2012-07-02T18:47:46.613 回答
1

只是为了看看你是否可以浓缩product表达,我想出了这个:

>>> from itertools import product
>>> map(lambda x: sum(x, []), product(a, b))
[[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [1, 2, 3, 'e', 'f'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd'], [4, 5, 6, 'e', 'f'], [7, 8, 9, 'a', 'b'], [7, 8, 9, 'c', 'd'], [7, 8, 9, 'e', 'f']]
于 2012-07-02T18:47:56.170 回答