在python中用元组制作成员向量 [英] Make member vectors out of tuples in python

查看:132
本文介绍了在python中用元组制作成员向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组/列表列表. 示例:

I have a list of tuples/lists. Example:

a = [[1,2], [2,4], [3,6]]

鉴于所有子列表的长度相同,我希望将其拆分并接收每个成员的列表/向量.

Given all sub-lists are the same length I want to split them and receive lists/vectors for each member.

或合而为一[[1,2,3],[2,4,6]] 每个使用numpy或默认列表的解决方案都将得到认可.

Or in one [[1,2,3],[2,4,6]] Every solution using numpy or default lists would be appretiated.

我还没有找到一种方法来以Python的方式或通过使用除循环以外的任何其他功能来有效地做到这一点:

I have not found a way to do this pythonicly, or efficiently by using any other feature than loops:

def vectorise_pairs(pairs):
    return [[p[0] for p in pairs],
            [p[1] for p in pairs]
           ]

有更好的方法吗?

推荐答案

由于您标记了numpy,所以my_array.T会转置my_array.

Since you tagged numpy, my_array.T transposes my_array.

>>> import numpy as np
>>> a = [[1,2], [2,4], [3,6]]
>>> np.array(a).T
array([[1, 2, 3],
       [2, 4, 6]])

或者,您可以使用np.transpose(甚至可以接受列表).

Alternatively, you can use np.transpose (which even accepts lists).

>>> np.transpose(a)
array([[1, 2, 3],
       [2, 4, 6]])

这篇关于在python中用元组制作成员向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆