【问题标题】:Using a dictionary to index parallel arrays?使用字典来索引并行数组?
【发布时间】:2014-03-04 13:09:02
【问题描述】:
【问题讨论】:
-
虽然这里不一定需要,但创建一个具有 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 循环第一部分周围的括号(即在 for 和 in 关键字之间)。我只是为了增强代码的可读性而使用它们。
与WeaselFox's answer 一样,d[some_start_value] 现在将保存相应的shape、length 和end 值。
【解决方案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
等等。