配对列表列表中的元素以形成新列表 [英] Pair elements from lists of list to form a new list
问题描述
我有一个类似以下的列表
I have a list of lists like the following,
a = [[ [1,2], [10, 3]], [[4,5], [6, 7]]]
我需要以这种方式将最里面的列表元素配对
I need to pair the inner most list elements this way,
a = [[[1, 10], [2, 3]], [[4, 6], [5, 7]]].
简单的方法如下:
pairings_ = []
for ind in a:
pairings_.append([[x, y] for x in ind[0] for y in ind[1])
如果ind中的列表大于2,则将导致内存错误.
例如,
如果ind [0],[1、2],[10、3],[7、8]中有三个内部列表,则配对将为[1、10、7]和[2、3、8] .
假设[[1,10],[2,3]]和[[4,6],[5,7]]的内部列表的长度将始终相等.
This would cause memoryerror if the lists inside ind are more than 2.
For example,
If there were three inner lists in ind[0], [1, 2], [10, 3], [7, 8], then the pairing would be [1, 10, 7] and [2, 3, 8].
The assumption is the length of inner list of [[1, 10], [2, 3]] and [[4,6], [5, 7]] will always be equal.
我将如何以尽可能多的pythonic/numpy/最有效的方式进行此操作?
How would I go about doing this in the most pythonic / numpy / efficient way possible?
推荐答案
我将如何以尽可能多的pythonic/numpy/最有效的方式进行此操作?
How would I go about doing this in the most pythonic / numpy / efficient way possible?
您可以使用 np.transpose
和将其转换回列表.
You can use np.transpose
and convert it back to list.
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]]]
这篇关于配对列表列表中的元素以形成新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!