简体   繁体   English

numpy数组列出格式

[英]numpy array to list formatting

How would i format a numpy array of form 我如何格式化一个numpy形式的数组

data1 = np.array([[0,0,0],[0,1,1],[1,0,1],[1,1,0]])

to a list in this format: 到这种格式的列表:

data = [
       [[0,0], [0]],
       [[0,1], [1]],
       [[1,0], [1]],
       [[1,1], [0]]
    ] 

I tried using two for loops 我尝试使用两个for循环

for i in range(len(data)):
    for j in range(3):
       if j == 2:
            va[i] = data1[i][j]
       else:            
            sa[i] = data1[i][j]

but that gives me an index out of bounds error. 但这给了我一个索引超出界限的错误。 I would love some ideas on how to go about this 我会喜欢有关如何解决这个问题的一些想法

Use list comprehension and slicing: 使用列表理解和切片:

>>> data1 = np.array([[0,0,0],[0,1,1],[1,0,1],[1,1,0]])
>>> print [[x[:2].tolist(), x[2:].tolist()] for x in data1]
[[[0, 0], [0]],
 [[0, 1], [1]],
 [[1, 0], [1]],
 [[1, 1], [0]]]

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

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