首页 > 解决方案 > 在 Python 中删除方括号

问题描述

我有这个输出:

[[[-0.015,  -0.1533,  1.    ]]

 [[-0.0069,  0.1421,  1.    ]]

...

 [[ 0.1318, -0.4406,  1.    ]]

 [[ 0.2059, -0.3854,  1.    ]]]

但我想删除剩下的方括号,结果如下:

[[-0.015  -0.1533  1.    ]

 [-0.0069  0.1421  1.    ]

 ...

 [ 0.1318 -0.4406  1.    ]

 [ 0.2059 -0.3854  1.    ]]

我的代码是这样的:

XY = []
for i in range(4000):
     Xy_1 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 1]
     Xy_0 = [round(random.uniform(-0.5, 0.5), 4), round(random.uniform(-0.5, 0.5), 4), 0]
     Xy.append(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85)))

Xy = np.asarray(Xy)

标签: pythonpython-3.xlistflatten

解决方案


您可以使用numpy.squeeze从数组中删除 1 个暗淡

>>> np.squeeze(Xy)
array([[ 0.3609,  0.2378,  0.    ],
       [-0.2432, -0.2043,  1.    ],
       [ 0.3081, -0.2457,  1.    ],
       ...,
       [ 0.311 ,  0.03  ,  1.    ],
       [-0.0572, -0.317 ,  1.    ],
       [ 0.3026,  0.1829,  1.    ]])

或重塑使用numpy.reshape

>>> Xy.reshape(4000,3)
array([[ 0.3609,  0.2378,  0.    ],
       [-0.2432, -0.2043,  1.    ],
       [ 0.3081, -0.2457,  1.    ],
       ...,
       [ 0.311 ,  0.03  ,  1.    ],
       [-0.0572, -0.317 ,  1.    ],
       [ 0.3026,  0.1829,  1.    ]])
>>>

推荐阅读