List to array conversion to use ravel() function

PythonArraysListNumpy

Python Problem Overview


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

Python Solutions


Solution 1 - Python

Use numpy.asarray:

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

Solution 2 - Python

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)

Solution 3 - Python

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)

Solution 4 - Python

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.

Solution 5 - Python

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)

Solution 6 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2229953View Question on Stackoverflow
Solution 1 - PythonA. RodasView Answer on Stackoverflow
Solution 2 - PythonUszkai AttilaView Answer on Stackoverflow
Solution 3 - PythonD_CView Answer on Stackoverflow
Solution 4 - PythonPaul PanzerView Answer on Stackoverflow
Solution 5 - PythonVinayView Answer on Stackoverflow
Solution 6 - PythonMayank SharmaView Answer on Stackoverflow