Python 将列表中的元素配对以形成新列表

Python 将列表中的元素配对以形成新列表,python,numpy,Python,Numpy,我有一个列表,如下所示 a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]] pairings_ = [] for ind in a: pairings_.append([[x, y] for x in ind[0] for y in ind[1]) 我需要以这种方式配对最内部的列表元素 a = [[[1, 10], [2, 3]], [[4, 6], [5, 7]]]. straighforward方法如下: a = [[ [1,2], [10, 3

我有一个列表,如下所示

a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]]
pairings_ = []
for ind in a:
    pairings_.append([[x, y] for x in ind[0] for y in ind[1])
我需要以这种方式配对最内部的列表元素

a = [[[1, 10], [2, 3]], [[4, 6], [5, 7]]]. 
straighforward方法如下:

a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]]
pairings_ = []
for ind in a:
    pairings_.append([[x, y] for x in ind[0] for y in ind[1])
如果ind中的列表超过2,则会导致memoryerror。
例如 如果在ind[0]、[1,2]、[10,3]、[7,8]中有三个内部列表,那么配对将是[1,10,7]和[2,3,8]。 假设[[1,10]、[2,3]]和[[4,6]、[5,7]]的内部列表长度始终相等

我将如何以最具pythonic/numpy/effective的方式进行这项工作

我将如何以最具pythonic/numpy/effective的方式进行这项工作

您可以使用并将其转换回列表

In [1]: import numpy as np


In [2]: a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]]


In [3]: np.transpose(a, (0,2,1)).tolist()

Out[3]: [[[1, 10], [2, 3]], [[4, 6], [5, 7]]]
list(zip(*x))
是“转置”列表的一个众所周知的习惯用法。就你而言:

In [267]: a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]]                              
In [268]: [list(zip(*row)) for row in a]                                        
Out[268]: [[(1, 10), (2, 3)], [(4, 6), (5, 7)]]
Array
transpose
非常方便且富有表现力,但是从列表中创建数组可能会非常昂贵

In [272]: timeit [list(zip(*row)) for row in a]                                 
1.58 µs ± 23.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [273]: timeit np.transpose(a, (0,2,1)).tolist()                              
11.8 µs ± 217 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
从定时循环中删除阵列:

In [274]: %%timeit arr = np.array(a) 
     ...: np.transpose(arr, (0,2,1))                                                               
1.47 µs ± 11.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

但与这些定时比较一样,在处理较大的列表时,结果可能会有所不同。

所以您只想切换5s和6s?这里的目标有点不明确如果一个数组有3个元素,其余的有2个元素,那么您想对a中的行的剩余元素
[[[*map(list,zip(*row))]做什么来只获取列表。没有慢多少。