我有 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 中该怎么做?? 请帮忙
这不是用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(]]
您可以使用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))]
结果:
[[(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)]]