[英]how to convert array of array to single array in Python
here is my array, i tried some slicing operation这是我的数组,我尝试了一些切片操作
But it did not work但它没有用
can someone tell me how to do that?有人可以告诉我该怎么做吗?
type is numpy.ndarray类型为 numpy.ndarray
x=[[10 34]
[34 45]
[12 12]
[12 34]
[23 23]]
I want to get a output like this -:我想得到一个像这样的 output -:
x=[10 34
34 45
12 12
12 34
23 23]
if如果
You can do by:你可以这样做:
import numpy as np
x=[[10, 34],
[34, 45],
[12, 12],
[12, 34],
[23, 23]]
First without numpy:首先没有 numpy:
flatten_x = [item for sublist in x for item in sublist]
Second with flatten:第二个扁平化:
flatten_x = np.array(x).flatten().tolist()
Third with ravel which is faster among all:第三个是ravel,它是最快的:
flatten_x = np.array(x).ravel()
Fourth with reshape:第四,重塑:
flatten_x = np.array(x).reshape(-1)
Output: Output:
print(flatten_x)
You can try x.reshape(-1)
and if you want to convert it to list then you can use list(x.reshape(-1))
您可以尝试
x.reshape(-1)
,如果要将其转换为列表,则可以使用list(x.reshape(-1))
You can simply use the numpy function ravel as您可以简单地使用 numpy function ravel as
a = np.array([[1,2,3], [4,5,6]])
a.ravel()
Result would be: array([1, 2, 3, 4, 5, 6])结果将是:array([1, 2, 3, 4, 5, 6])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.