简体   繁体   English

如何在 Python 中将列表转换为一维数组?

[英]How to convert a list to an 1D array in Python?

Trying to convert a list to 1D array and that list contain arrays like this尝试将列表转换为一维数组,并且该列表包含 arrays 像这样

from

[array([1145,  330, 1205,  364], dtype=int64),
 array([1213,  330, 1247,  364], dtype=int64),
 array([ 883,  377, 1025,  412], dtype=int64),
 array([1038,  377, 1071,  404], dtype=int64),
 array([1085,  377, 1195,  405], dtype=int64),
 array([1210,  377, 1234,  405], dtype=int64)]

Required必需的

array([array([1145,  330, 1205,  364], dtype=int64),
       array([[1213,  330, 1247,  364], dtype=int64),
       array([883,  377, 1025,  412], dtype=int64),
       array([1038,  377, 1071,  404], dtype=int64),
       array([1085,  377, 1195,  405], dtype=int64),
       array([1085,  377, 1195,  405], dtype=int64), dtype=object))

tried this code but getting 2D array but need 1D array like above尝试了这段代码,但得到了二维数组,但需要像上面一样的一维数组

art = []
for i in boxs:
    art.append(np.array(i, dtype=np.int64))
new_ary = np.array(art)
new_ary

use .reshape(-1) on the individual arrays inside that list.在该列表中的单个 arrays 上使用.reshape(-1)

Your question is little ambiguous.你的问题有点模棱两可。 Your input is already a 2D and in您的输入已经是 2D 并且在

for i in boxs:
    art.append(np.array(i, dtype=np.int64))

i represents a list in each iteration. i表示每次迭代中的一个列表。 So, You are appending a list each time in art .因此,您每次都在art中附加一个列表。

You can try new_ary = new_ary.flatten() .您可以尝试new_ary = new_ary.flatten() It will give you它会给你

[1145  330 1205  364 1213  330 1247  364  883  377 1025  412 1038  377 1071  404 1085  377 1195  405 1210  377 1234  405]

Otherwise, provide an output to clarify your question.否则,请提供 output 来澄清您的问题。

While you are changing the list of arrays to an array of arrays with dtype=object , the value in the array is still int.当您将 arrays 列表更改为 dtype dtype=object的 arrays 数组时,数组中的值仍然是 int。

np.array(a, dtype=object)
array([[1145, 330, 1205, 364],
       [1213, 330, 1247, 364],
       [883, 377, 1025, 412],
       [1038, 377, 1071, 404],
       [1085, 377, 1195, 405],
       [1210, 377, 1234, 405]], dtype=object)

type(np.array(a, dtype=object)[0][0])
Out[151]: int

Update更新

If you want to flatten the 2D array to a 1D array, you can use np.ravel如果要将二维数组展平为一维数组,可以使用np.ravel

np.ravel(a)
array([1145,  330, 1205,  364, 1213,  330, 1247,  364,  883,  377, 1025,
        412, 1038,  377, 1071,  404, 1085,  377, 1195,  405, 1210,  377,
       1234,  405], dtype=int64)

Or let's say you want a 1D list, you can first do map to convert the array to list and then do reduce或者假设你想要一个一维列表,你可以先做map将数组转换为列表,然后做reduce

from functools import reduce

mylist = list(map(list, a))

print(reduce((lambda x, y: x+y) , mylist))
[1145, 330, 1205, 364, 1213, 330, 1247, 364, 883, 377, 1025, 412, 1038, 377, 1071, 404, 1085, 377, 1195, 405, 1210, 377, 1234, 405]

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

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