[英]how can i split each list entry at the first two spaces and add them all into a new list
[英]How can I make a new list that has the first element of each of the list but split into 3?
如果我从这个开始
A = [[1,3,5,7,2,2], [2,3,1,2,1,1]]
B = [[3,2,5,5,6,6], [2,1,4,2,7,2]]
C = [[1,0,2,4,8,2], [9,7,2,2,7,2]]
我怎样才能实现这个 output?
[[1,3],[5,7],[2,2],[3,2],[5,5],[6,6],[1,0],[2,4],[8,2]]
如果它是列表,你可以做一个嵌套的 for 循环:
result = []
for list_ in [A,B,C]:
for i in range(int(len(list_[0])/2)):
result.append(list_[0][i*2:i*2+2])
[[1, 3], [5, 7], [2, 2], [3, 2], [5, 5], [6, 6], [1, 0], [2, 4], [8, 2]]
或者列表理解
[list_[0][i*2:i*2+2] for list_ in [A,B,C] for i in range(int(len(list_[0])/2))]
如果是 numpy 数组,可以使用 concatenate 和 reshape
concat_array = np.concatenate((A[0],B[0],C[0]))
concat_array.reshape(9,2)
array([[1, 3],
[5, 7],
[2, 2],
[3, 2],
[5, 5],
[6, 6],
[1, 0],
[2, 4],
[8, 2]])
numpy 爱好者不会喜欢它,但您可以提取第一个元素作为常规 python 列表并加入它们(下面的first_elems
),然后从该列表中取出成对元素并转换回 numpy 数组。
from numpy import array
A = array([[1,3,5,7,2,2], [2,3,1,2,1,1]])
B = array([[3,2,5,5,6,6], [2,1,4,2,7,2]])
C = array([[1,0,2,4,8,2], [9,7,2,2,7,2]])
first_elems = list(A[0]) + list(B[0]) + list(C[0])
array(list(zip(first_elems[::2], first_elems[1::2])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.