【发布时间】:2021-01-04 09:41:17
【问题描述】:
我是编程新手,几乎不懂术语,所以请原谅我可能遇到的任何基本问题。
我正在尝试列出一个数组数组。
我在二维数组上编写了一个函数,该函数列出了数组中的最大值及其出现的点。这些点(最大值)形成数组[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_pos_array 也视为一个列表,但我仍然很好奇为什么会发生这种情况。
【问题讨论】:
-
因为
numpy.ndarray.__repr__是这样定义的......我不确定你到底在问什么。 -
我什至不知道
.__repr__是什么意思。 -
当您
print(some_object)时,正在打印的实际str对象是__str__或__repr__返回的字符串。 See this question for the difference。无论如何,重点是,因为它就是这样设计的。设计numpy的人可以拥有print(my_array)打印banana或foo如果他们想要。 -
感谢您的解释。
标签: python arrays list numpy multidimensional-array