删除 Python 中的方括号

Remove square brackets in 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)

尝试扩展方法。

Xy.extend(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85)))

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

>>> 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.    ]])
>>>

你可以用这个random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85))[0]

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]
     # Pythonic way :-)
     Xy.append(random.choices(population=(Xy_0, Xy_1), weights=(0.15, 0.85))[0])

Xy = np.asarray(Xy)
print(Xy)

输出

[[ 0.3948  0.0915  1.    ]
 [ 0.4197 -0.344   1.    ]
 [-0.4541  0.3192  1.    ]
 [ 0.3285  0.0453  1.    ]
 [-0.0171 -0.3088  1.    ]
 [ 0.2958 -0.2757  1.    ]
 [-0.1303  0.1581  0.    ]
 [-0.4146 -0.4454  1.    ]
 [ 0.0247  0.325   1.    ]
 [-0.227   0.139   1.    ]]

您可以尝试使用 sum 删除 1dim。

a=[ [[-0.015,  -0.1533,  1.    ]],
    [[-0.0069,  0.1421,  1.    ]],
    ...
    [[ 0.1318, -0.4406,  1.    ]],
    [[ 0.2059, -0.3854,  1.    ]] ]

sum(a,[])
'''
[[-0.015,  -0.1533,  1.    ],
  [-0.0069,  0.1421,  1.    ],
  ...
  [ 0.1318, -0.4406,  1.    ],
  [ 0.2059, -0.3854,  1.    ]]
'''