如何将一组Python列表转换为numpy数组?

qlzsbp2j  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(102)

我需要将一组数组的类型设置为np.ndarray类型。由于我需要多次执行,我尝试了for循环,在执行循环时,似乎正确地从list转换为np.ndarray,但一旦结束,每个数组仍然是list类型,下面的这个区块帮助我意识到它正在发生,但我不知道它为什么会发生
那么,为什么会发生这种情况?以及如何修复它?提前感谢

import numpy as np

pos = [1,1,1]
vel = [1,1,2]
# vel = np.array([1,1,2])
accel = [1,1,3]

print('\nredefining...')
for elem in [pos,vel,accel]:
    # checks if the array is of the np.ndarray class
    print(type(elem))
    if not isinstance(elem, np.ndarray):
        elem = np.array(elem)
        print(type(elem))
    print('---------------------------')

print('\nafter the redefinition:')

print(type(pos))
print(type(vel))
print(type(accel))

字符串
产出:

redefining...
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------

after the redefinition:
<class 'list'>
<class 'list'>
<class 'list'>

vcudknz3

vcudknz31#

你不能重新赋值,你的elem变量在循环中的每一步都会被覆盖,原始变量保持不变。
简单用途:

pos = np.array(pos)
vel = np.array(vel)
accel = np.array(accel)

字符串
或者使用@jared建议的asarray,如果数组已经是一个数组,则避免复制数组:

pos = np.asarray(pos)
vel = np.asarray(vel)
accel = np.asarray(accel)


作为一个班轮:

pos, vel, accel = map(np.asarray, (pos, vel, accel))


或者,如果你真的想检查类型(这是不需要IMO):

def to_numpy(elem):
    return elem if isinstance(elem, np.ndarray) else np.array(elem)

pos = to_numpy(pos)
vel = to_numpy(vel)
accel = to_numpy(accel)


最后一个建议,如果你有很多变量,使用容器

items = {'pos': pos, 'vel': vel, 'accel': accel}

arrays = {k: elem if isinstance(elem, np.ndarray) else np.array(elem)
          for k, v in items.items()}

0sgqnhkj

0sgqnhkj2#

正如马克·托洛宁注意到的那样,

import numpy as np

pos = [1, 1, 1]
vel = [1, 1, 2]
accel = [1, 1, 3]

arrays = [pos, vel, accel]

for i in range(len(arrays)):
    if not isinstance(arrays[i], np.ndarray):
        arrays[i] = np.array(arrays[i])

# Update the original variables
pos, vel, accel = arrays

print('\nAfter the redefinition:')
print(type(pos))   # <class 'numpy.ndarray'>
print(type(vel))   # <class 'numpy.ndarray'>
print(type(accel)) # <class 'numpy.ndarray'>

字符串

hec6srdp

hec6srdp3#

这是因为你改变了“elem”的类型,它接受循环中变量的值,而不是变量本身的类型。你可以通过fe.这样做来解决这个问题:

import numpy as np

pos = [1,1,1]
vel = [1,1,2]
# vel = np.array([1,1,2])
accel = [1,1,3]

print(type(pos))
print(type(vel))
print(type(accel))

print('\nredefining...')

pos = np.array(pos)
vel = np.array(vel)
accel = np.array(accel)

print('\nafter the redefinition:')

print(type(pos))
print(type(vel))
print(type(accel))

字符串

相关问题