附加 ndarray 和 lists 时出现问题。我解决了它,但无法如愿以偿

Problem with appending with ndarray and lists. I solved it but couldn't get it as I want

提问人:knowledge_seeker 提问时间:3/8/2022 最后编辑:knowledge_seeker 更新时间:3/8/2022 访问量:33

问:

场景:我有一个函数 myfunction(),它总是生成 [[0, 5]] 形式的 ndarray。我调用 myfunction() 三次(比如说),每次我都会将输出附加到一个名为 nos_indices 的数组中。如下图所示。

nos_indices=myfunction(some argument) #I call once like this first

for loop:
  nos_indices.append( myfunction(some argument)) 

def myfunction(the argument):
    ....
    ranges_ndarray = np.where(absdiff == 1)[0].reshape(-1, 2)   #this gives [[0, 5]]

问题:但是当我调用三次时,附加项会这样做,以后我很难用这种结构进行索引。[[0, 5], [[0, 5]], [[0, 5]]]

我的问题:所以,我在之后添加了这一行ranges=ranges_ndarray.tolist()ranges_ndarray

我的 soln. 工作 lil,但不是我想要的:现在,函数返回哪个很好。但是就在 2 次调用中,我看到附加物正在做。这对我来说也是错误的,因为我希望追加后的输出是这样的[0, 5][0, 5, [0, 5]][[0, 5], [0, 5], ...]

任何人都可以建议如何处理这个问题并获得像.我不知道如何同时处理 myfunction 和附加输出以生成我想要的形式。[[0, 5], [0, 5], ...]

python 多维数组 numpy-ndarray 嵌套列表

评论


答:

0赞 knowledge_seeker 3/8/2022 #1

我发现这是怎么回事。我第一次调用 myfunction 是 ,然后是一个不断附加到此nos_indices的 for 循环。因此,第一次调用给出了 which 是可以的,但是当第二次使用 调用时,它导致输出为 。因此,要得到 [[0, 5], [0, 5], ...]我更改了第一个电话,如下所示。nos_indices=myfunction(some argument)[0, 5]nos_indices.append( myfunction(some argument))[0, 5, [0, 5]]

nos_indices=myfunction(some argument)  #THIS IS REPLACED BY NEXT TWO LINES

nos_indices=[]
nos_indices.append(myfunction(some argument))
#then the for loop and subsequent append code as in question

即使在第二次调用和相应的附加之后,此更改仍保持第一个完整,从而给了我[0, 5][[0, 5], [0, 5]]