我有2个列表/矩阵
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
b = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
我希望得到像
这样的结果result =
[[(1, 10), (1, 11), (1, 12), (2, 10), (2, 11), (2, 12), (3, 10), (3, 11), (3, 12)],
[(4, 13), (4, 14), (4, 15), (5, 13), (5, 14), (5, 15), (6, 13), (6, 14), (6, 15)],
[(7, 16), (7, 17), (7, 18), (8, 16), (8, 17), (8, 18), (9, 16), (9, 17), (9, 18)]]
在python中做什么?请帮忙
答案 0 :(得分:4)
这不是在python中编写列表的正确方法。我也冒昧地假设每一行都是一个清单。因此 a 和 b 是列表的列表。
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
b= [
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]
]
result = []
for ix, i in enumerate(a):
temp = []
for j in i:
for k in b[ix]:
temp.append((j,k))
result.append(temp)
print(result)
<[>([1,10],(1,11),(1,12),(2,10),(2,11),(2,12),(3,10),(3, 11),(3,12)],[[4,13],(4,14),(4,15),(5,13),(5,14),(5,15) , (6,13),(6,14),(6,15)],[[7,16],(7,17),(7,18),(8,16),(8) , 17),(8,18),(9,16),(9,17),(9,18)]]
答案 1 :(得分:3)
您可以使用#[derive(SecondProcMacro)]
:
itertools.product
结果:
from itertools import product
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
b = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
res = [list(product(a[i], b[i])) for i in range(len(a))]