简体   繁体   English

Numpy Array 对象在函数中转换为 List 对象?

[英]Numpy Array object converting to List object in function?

I'm attempting to create a one-dimensional cellular automata.我正在尝试创建一个一维元胞自动机。 For a given rule (between 1 and 255), the number is converted into the corresponding 8-digit binary number and paired to all 8 possible combinations of 0's and 1's.对于给定的规则(1 到 255 之间),数字被转换为相应的 8 位二进制数,并与 0 和 1 的所有 8 种可能组合配对。

The code seems to work fine outside of putting it in a function.除了将其放入函数之外,该代码似乎还可以正常工作。 However, when I run the second half, it gives me the AttributeError: 'list' object has no attribute 'shape'.但是,当我运行后半部分时,它给了我 AttributeError: 'list' object has no attribute 'shape'。 I defined 'values' as a Numpy array and if I run the code without the stepping portion, it stays as an array.我将“值”定义为一个 Numpy 数组,如果我在没有步进部分的情况下运行代码,它仍然是一个数组。 I am unsure what is going on.我不确定发生了什么。 Any guidance would be appreciated!任何指导将不胜感激!

def cellular_step(value, rule=110):

    blist = np.unpackbits(np.uint8(rule))
    truple = [(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)]

    lookup_dict = {}
    for indx,lmr in enumerate(truple):
        lookup_dict[lmr] = blist[indx]

    next_step = np.array([],dtype=np.int8)

    for i in range(value.shape[0]):
        indices = range(i-1,i+2)
        neighbourhood = value.take(indices,mode='wrap')
        b = tuple(neighbourhood)
        a = lookup_dict.get(b)
        next_step = np.append(next_step,a)

    return[next_step]



value = np.zeros(5, dtype=np.int8)
value[ len(value)//2 ] = 1

nsteps = 10
grid = np.ndarray( [nsteps,len(value)], dtype=np.int8)

for n in range(nsteps):
    value = cellular_step(value,rule=30)
    grid[n,:] = value

plt.imshow(grid)

At the end of cellular_step , you returned a list which is then assigned to the variable value .在结束cellular_step ,你回来,然后将其分配给变量列表value Thus value is no longer a Numpy array and hence do not have the attribute shape .因此value不再是一个 Numpy 数组,因此没有属性shape

Why do you return[next_step] ?你为什么return[next_step]

Doing return next_step is a priori what you are looking for.return next_step是你正在寻找的先验。


I defined 'values' as a Numpy array and if I run the code without the stepping portion, it stays as an array.我将“值”定义为一个 Numpy 数组,如果我在没有步进部分的情况下运行代码,它仍然是一个数组。

Actually not.其实并不是。 See,看,

>>> type(cellular_step(value, rule=30))
<type 'list'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM