问题:列表到数组的转换以使用ravel()函数
我在python中有一个列表,我想将其转换为数组以能够使用ravel()
函数。
I have a list in python and I want to convert it to an array to be able to use ravel()
function.
回答 0
Use numpy.asarray
:
import numpy as np
myarray = np.asarray(mylist)
回答 1
创建一个int数组和一个列表
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)
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)
回答 2
我想要一种无需使用额外模块即可执行此操作的方法。首先将列表转换为字符串,然后追加到数组:
dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
dataset_array.append(item)
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)
回答 3
如果您只想ravel
在自己的(嵌套,我要摆姿势?)列表上打电话,则可以直接执行此操作,numpy
将为您进行转换:
L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)
另外值得一提的是,你不必去通过numpy
所有。
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.
回答 4
使用以下代码:
import numpy as np
myArray=np.array([1,2,4]) #func used to convert [1,2,3] list into an array
print(myArray)
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)
回答 5
如果变量b有一个列表,则只需执行以下操作:
创建一个新变量“ a”为:a=[]
然后将列表分配给“ a”为:a=b
现在“ a”在数组中具有列表“ b”的所有组件。
因此您已成功将列表转换为数组。
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.