列表到数组转换使用 ravel()函数

我在 python 中有一个列表,我想把它转换成一个数组,以便能够使用 ravel()函数。

642678 次浏览

Use numpy.asarray:

import numpy as np
myarray = np.asarray(mylist)

if variable b has a list then you can simply do the below:

create a new variable "a" as: a=[] then assign the list to "a" as: a=b

now "a" has all the components of list "b" in array.

so you have successfully converted list to array.

I wanted a way to do this without using an extra module. First turn list to string, then append to an array:

dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
dataset_array.append(item)

create an int array and a list

from array import array
listA = list(range(0,50))
for item in listA:
print(item)
arrayA = array("i", listA)
for item in arrayA:
print(item)

Use the following code:

import numpy as np


myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array
print(myArray)

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.