Python3.7 NumPy数组打印列表在实际数组前面打印“array”。为什么?

2024-10-01 07:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,几乎不懂术语,所以请原谅我可能会问的任何基本问题

我试图列出一组数组

我已经在2D数组上编写了一个函数,列出了数组中的最高值和出现的点。这些点(最大值)形成数组[i,j],为了便于显示,我希望将其收集到单个numpy数组或列表max_p。据我所知,最明智的方法是使用numpy.append( max_p, [i,j] )。问题是它将[i,j])合并到max_p数组中,这样我就得到了一个单值数组,而不是有序对数组。所以我决定把整件事都列成一个清单

这很有效,在大多数情况下,我得到了我的有序配对列表,我可以在一行中打印出来

但是,大列表max_p中的数组并没有像[a,b]那样打印。它们被打印为array([a,b])。无论我是使用max_p.tolist()还是list(max_p),这种情况都会发生

当然,如果没有实际的代码,这一切都没有意义,这里是:

def maxfinder_2D(array):
    maxima_array = numpy.array([]) # placeholder array
    for i in range(0, 422): # side note: learn how to get dim.s of 
                            # a multidimensional array
        x_array = array [i,:] # set array to be the i-th row
       # row_max = numpy.append(row_maxfinder_1D(x_array))
        maxima_array = numpy.append(maxima_array, numpy.array([maxfinder_1D(x_array)]))
            # We construct a new array, maxima_array, to list the 
            # maximum of every row in the plot.
            # The maximum, then, must be the maximum of this array.
    max_2D = maxfinder_1D(maxima_array)
    print("The maximum value in the image is: ", max_2D)
    global max_p
    max_p = []
    # This gives us the maximum value. Finding its location is another
    # step, though I do wish I could come up with a way of finding the
    # location and the maximum in a single step.
    for i in range(0,422): 
        for j in range(400): # the nested loop runs over the entire array
            val = img[i][j]
            if val == max_2D:
                max_pos_array = numpy.array([])
                max_pos_array = numpy.append(max_pos_array , i)
                max_pos_array = numpy.append(max_pos_array , j)
                list(max_pos_array)
                    #print(max_pos_array.tolist())
                max_p.append(max_pos_array)
    return max_2D
print("The function attains its maximum of ",maxfinder_2D(img)," on ", max_p)

以下是(部分)输出:

The maximum value in the image is: 255.0 The function attains its maximum of 255.0 on [array([200., 191.]), array([200., 192.]), array([201., 190.]), array([201., 193.]), array([202., 190.]), array([202., 193.]), array([203., 193.]), array([204., 191.]),

我希望数组显示为简单的,例如,[200. , 191.]

为什么会出现这种“工件”?它是否与numpy如何将数组与列表关联有关

编辑:事实证明,我所需要做的就是将max\u pos\u数组也视为一个列表,但我仍然很好奇为什么会发生这种情况。


Tags: oftheinposnumpy列表数组array
2条回答

Python对象具有reprstr显示方法

In [1]: x = np.arange(3)
In [2]: x
Out[2]: array([0, 1, 2])
In [3]: repr(x)
Out[3]: 'array([0, 1, 2])'
In [4]: str(x)
Out[4]: '[0 1 2]'
In [5]: print(x)
[0 1 2]

对于列表,它们是相同的,[,]用于列表本身,repr用于元素:

In [6]: alist = [x]
In [7]: alist
Out[7]: [array([0, 1, 2])]
In [8]: repr(alist)
Out[8]: '[array([0, 1, 2])]'
In [9]: str(alist)
Out[9]: '[array([0, 1, 2])]'

也许您可以尝试使用数组的字符串表示形式

print("The function attains its maximum of ",maxfinder_2D(img)," on ", np.array2string(max_p))

相关问题 更多 >