简体   繁体   English

向量元组列表 - >两个矩阵

[英]List of tuples of vectors --> two matrices

In Python, I have a list of tuples, each of them containing two nx1 vectors. 在Python中,我有一个元组列表,每个元组都包含两个nx1向量。

data = [(np.array([0,0,3]), np.array([0,1])),
        (np.array([1,0,4]), np.array([1,1])),
        (np.array([2,0,5]), np.array([2,1]))]

Now, I want to split this list into two matrices, with the vectors as columns. 现在,我想将此列表拆分为两个矩阵,向量为列。
So I'd want: 所以我想要:

x = np.array([[0,1,2],
              [0,0,0],
              [3,4,5]])

y = np.array([[0,1,2],
              [1,1,1]])


Right now, I have the following: 现在,我有以下内容:

def split(data):
    x,y = zip(*data)

    np.asarray(x)
    np.asarray(y)
    x.transpose()
    y.transpose()

    return (x,y)

This works fine, but I was wondering whether a cleaner method exists, which doesn't use the zip(*) function and/or doesn't require to convert and transpose the x and y matrices. 这工作正常,但我想知道是否存在更清晰的方法,它不使用zip(*)函数和/或不需要转换和转置x和y矩阵。

This is for pure entertainment, since I'd go with the zip solution if I were to do what you're trying to do. 这是纯粹的娱乐,因为如果我要做你想做的事情,我会使用zip解决方案。

But a way without zipping would be vstack along your axis 1. 但是没有zipping的方法vstack沿着轴1的vstack

a = np.array(data) 
f = lambda axis: np.vstack(a[:, axis]).T 

x,y = f(0), f(1)

>>> x
array([[0, 1, 2],
       [0, 0, 0],
       [3, 4, 5]])

>>> y
array([[0, 1, 2],
       [1, 1, 1]])

Comparing the best elements of all previously proposed methods, I think it's best as follows*: 比较所有先前提出的方法的最佳元素,我认为最好如下*:

def split(data):
    x,y = zip(*data)         #splits the list into two tuples of 1xn arrays, x and y

    x = np.vstack(x[:]).T    #stacks the arrays in x vertically and transposes the matrix
    y = np.vstack(y[:]).T    #stacks the arrays in y vertically and transposes the matrix

    return (x,y)

* this is a snippet of my code *这是我的代码片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM