List to array conversion to use ravel() function

Question:

I have a list in python and I want to convert it to an array to be able to use ravel() function.

Asked By: user2229953

||

Answers:

Use numpy.asarray:

import numpy as np
myarray = np.asarray(mylist)
Answered By: A. Rodas

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.

Answered By: Mayank Sharma

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)
Answered By: D_C

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)
Answered By: Uszkai Attila

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)
Answered By: Vinay

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.

Answered By: Paul Panzer
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.