如何连接两个元组并保持它们的形状



我有两个列表,

train = [[1, 2], [0, 2], [0, 1]]
test = [0, 1, 2] 

我能用NumPy或for循环做些什么来使最终结果看起来像这样:

final = [([1, 2], [0]), ([0, 2], [1]), ([0, 1], [2])]

提前谢谢!

您可以使用zip函数来执行此操作:

final = list(zip(train, [[t] for t in test]))  

zip函数将可迭代容器中的相应项配对,并返回一个zip项,该项可以转换为列表,以获得所需的结果。

进一步阅读:https://docs.python.org/3.3/library/functions.html#zip

您不可能以numpy的形式进行这种类型的输出,因为numpy是与张量/数组一起使用的形式。因此,如果你的输入是这样的,你必须将它们转换为张量,结果将是一个由2个张量组合的张量:

train = np.asarray(train) #3x2 shape
test = np.asarray(test).reshape(-1,1) # reshape to the same shape with 3x1 shape
np.append(train,test,axis=1)
array([[1, 2, 0],
[0, 2, 1],
[0, 1, 2]]) #output

否则,如果你使用zip和list来迭代列表训练和列表测试,得到你的结果会更好:

list(zip(train, [list(t) for t in test]))

最新更新