0

我目前正在研究一个递归函数来搜索表示沿河位置的字典。start字典使用作为键索引 4 个并行数组。

并行阵列:

start= 流量累积较小的端点位置,

end= 另一个端点的位置(流量累积较大),

length= 段长度,和;

shape= 实际形状,面向从头到尾运行。

字典:

G = {}
for (st,sh,le,en) in zip(start,shape,length,end):
    G[st] = (sh,le,en)

我的目标是从一个由 表示的起点沿河向下搜索,p并选择一个以 2000 米(由 表示x)间隔的位置,直到end. 这是我正在使用 Python 处理的递归函数:

def Downstream (p, x, G):
...     e = G[p]
...     if (IsNull(e)):
...         return ("Not Found")
...         if (x < 0):
...             return ("Invalid")
...             if (x < e.length):
...                 return (Along (e.shape, x))
...                 return (Downstream (e.end, x-e.length,G))

目前,当我输入Downstream ("(1478475.0, 12065385.0)", 2000, G)它时,它会返回一个 keyerror。我已经检查key in G并且该键返回false,但是当我搜索G.keys ()它时,它返回由start包含给出false的键表示的所有键。

例如一个键是(1478475.0, 12065385.0). 我已将此键用作文本和 2 个双精度值的元组,并且两次都返回了 keyerror。

错误:

Runtime error
Trackback (most recent call last):
 File “&lt;string>”, line 1, in <module>
 File “&lt;string>”, line 1, in Downstream
KeyError:  (1478475.0, 12065385.0)

是什么导致了密钥错误,我该如何解决这个问题以达到我的目标?

我在 ArcGIS 中使用 Python,因为这是使用折线 shapefile 中的属性表,这是我第一次尝试使用递归函数。

这个问题和答案是我在组织数据和编写这个递归函数时如何达到这一点的。

https://gis.stackexchange.com/questions/87649/select-points-approx-2000-metres-from-another-point-along-a-river

例子:

>>> G.keys ()
[(1497315.0, 11965605.0), (1502535.0, 11967915.0), (1501785.0, 11968665.0)...

>>> print G
{(1497315.0, 11965605.0): (([1499342.3515172896, 11967472.92330054],), (7250.80302528,), (1501785.0, 11968665.0)), (1502535.0, 11967915.0): (([1502093.6057616705, 11968248.26139775],), (1218.82250994,), (1501785.0, 11968665.0)),...
4

1 回答 1

2

您的功能无法正常工作有五个主要原因:

  1. 语法是关闭的——缩进在 Python 中很重要;
  2. 您不检查是否p in G每次都Downstream被调用(第一个键可能存在,但是以后的递归调用呢?);
  3. 你有太多的return点,例如你的最后一行永远不会运行(函数输出应该是什么?);
  4. 您似乎正在e = (sh, le, en)通过属性 ( e.end) 访问 3 元组;和
  5. 当您递归调用时,您正在从间隔长度中减去,因此该函数无法跟踪点应该相距多远 - 您需要将间隔和偏移量与开始分开。

相反,我认为您需要类似(未经测试!):

 def Downstream(start, interval, data, offset=0, out=None):
     if out is None:
         out = []
     if start in data:
         shape, length, end = data[start]
         length = length[0] 
         if interval < length:
             distance = offset
             while distance < length:
                 out.append(Along(shape, distance))
                 distance += interval
             distance -= interval
             Downstream(end, interval, data, interval - (length - distance), out)
         else:
             Downstream(end, interval, data, offset - length, out)
     return out

这将为您提供任何Along返回的列表。如果是原始的start not in data,它将返回一个空列表。

于 2014-03-05T17:01:13.310 回答