[英]Python: appending array index to list (.append)
提前感谢您的帮助。 我在将数组索引附加到列表时遇到麻烦。 我有一个包含起点(1366,1264)的数组counterStack,我在该起点上进行邻域搜索,对于满足条件设置的每个新索引,应将索引附加到counterStack上。 奇怪的是索引已正确附加到列表stack
,但没有附加到列表counterStack
。
这是因为我的if语句( if ([nx, ny] not in counterStack):
吗? 我知道它进入if语句,因为计数器的计数在每次迭代中都加1。 索引将被添加到堆栈两次。 因此,我将counterStack设置为仅考虑一次索引,以便可以限制总体编辑像素。 到运行结束时,应该将121个indec附加到counterStack上。
这是结果的示例:
count = 1
[(1366, 1264), (1365, 1263)]
count = 2
[(1366, 1264), (1365, 1264)]
count = 3
[(1366, 1264), (1365, 1265)]
count = 4
[(1366, 1264), (1366, 1265)]
count = 5
[(1366, 1264), (1367, 1265)]
count = 6
[(1366, 1264), (1367, 1264)]
count = 7
[(1366, 1264), (1367, 1263)]
count = 8
[(1366, 1264), (1366, 1263)]
count = 9
[(1366, 1264), (1365, 1262)]
这是我的一些代码:
neighbors = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]
mask = np.zeros_like(dem_arr, dtype = bool)
stack = [(1366, 1264)] # push start coordinate on stack
if (dem_arr[1366, 1264] > -100):
count = 0
while count <= 121:
x, y = stack.pop()
mask[x, y] = True
for dx, dy in neighbors:
nx, ny = x + dx, y + dy
if (0 <= nx < dem_arr.shape[0] and 0 <= ny < dem_arr.shape[1] and dem_arr[x, y] > -100 and dem_arr[nx, ny] > -100 and not mask[nx, ny] and abs(dem_arr[nx, ny] - dem_arr[x, y]) <= 5): #set elevation differnce
stack.append((nx, ny)) #if point is selected (true) array position gets added to stack and process runs over again
counterStack = [(1366, 1264)]
if ([nx, ny] not in counterStack):
counterStack.append((nx, ny))
dem_copy[(nx, ny)] = 8888
#dem_copy[randx, randy] = 8888
count += 1
print 'count = ', count
print counterStack
else:
print 'Point chosen has no data'
randx = random.randint(0, row-1)
randy = random.randint(0, col-1)
再次感谢您的帮助!
-R
您在for
循环的每次迭代中都设置counterStack = [(1366, 1264)]
,但是堆栈仅设置为counterStack = [(1366, 1264)]
引一次。
将counterStack = [(1366, 1264)]
到行stack = [(1366, 1264)]
counterStack = [(1366, 1264)]
的正下方,您应该会看到想要的内容。
同样如9000所示, (x, y)
表示由x
和y
组成的2元组。 [x, y]
是长度2的list
。您可以将结果与索引值分别进行比较: (x, y)[1]
将返回y
, [x, y][1]
也将返回y
。
但是,使用if ... not in counterStack
会比较每个2-tuple
(xx, yy)
在counterStack
到list
[nx, ny]
它永远不会返回False
,因为counterStack
将永远不会有一个list
。
这是您的问题:
counterStack = [(1366, 1264)] # counterStack contains a tuple
if ([nx, ny] not in counterStack): # counterStack is checked for a list
counterStack.append((nx, ny)) # counterStack adds another tuple
请注意, [1, 2]
和(1, 2)
是完全不同的东西。 他们不是彼此相等,所以in
没有做你所期望的东西。
我假设您统一使用2元组来表示一个位置。 元组是不可变的,并且大小固定,这对于坐标向量是完全有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.