【问题标题】:Using a dictionary to index parallel arrays?使用字典来索引并行数组?
【发布时间】:2014-03-04 13:09:02
【问题描述】:

我有 4 个基于表示地图属性的表的并行数组。每个数组有大约。 500 个值,但都具有相同数量的值。

数组是:

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

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

length = 段长度,并且;

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

我正在尝试创建一个数据结构,我可以从中使用递归函数来确定沿长度每 2000m 的起点和终点。

以下问题和答案描述了我想要完成的任务:

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

如何将这 4 个并行数组存储在以 start 为键的字典中?

我不熟悉编写函数、字典和在字典中使用数组。我正在尝试在 Python 中完成这项任务。

【问题讨论】:

  • 虽然这里不一定需要,但创建一个具有 start/end/length/shape 属性的class 可能会很有用。这样一来,您就可以拥有一个 RiverSegment 对象列表(或任何您想调用的对象),而不是四个属性列表。

标签: python arrays dictionary


【解决方案1】:

我想这就是你的意思:

d = {}
for i in range(len(start)):
   d[start[i]] = (shape[i],length[i],end[i])

所以现在d[some_start_value] 将保存相应的形状长度和结束值。

【讨论】:

    【解决方案2】:

    如果你想做更多的事情Python-esque,你可以使用enumerate

    d = {}
    for (i,st) in enumerate(start):
        d[st] = (shape[i],length[i],end[i])
    

    甚至更好 - zip:

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

    请注意,您可以省略 for 循环第一部分周围的括号(即在 forin 关键字之间)。我只是为了增强代码的可读性而使用它们。

    WeaselFox's answer 一样,d[some_start_value] 现在将保存相应的shapelengthend 值。

    【讨论】:

      【解决方案3】:

      除了以上答案,我建议使用namedtuple 来简化访问:

      from collections import namedtuple
      
      # This creates a namedtuple called GISData. Name of the object and name in the first argument 
      # should be the same. 
      GISData = namedtuple('GISData', 'start shape length end')
      
      # zip creates 1 list of 4-tuples from 4 single lists
      # There are other ways to write this; this is just the shortest for me.
      # Note that if you need this ordered, you should use an OrderedDict,
      # which is in the collections module in python 2.7+, or you can find
      # backported versions for python 2.6+. In those, the keys preserve ordering,
      # so can still be searched as a list, which is useful if you need to find e.g.
      # 479, which is not in the dictionary, but 400 and 500 are and you have to interpolate etc.
      
      GISDict = dict((x[0], GISData(*x)) for x in zip(start, shape, length, end))
      
      # The dictionary for any given start value
      # Access the 4 individual pieces by name, or by index
      GISDict[start_lookup].shape
      

      等等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-26
        • 1970-01-01
        • 2018-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        相关资源
        最近更新 更多