繁体   English   中英

循环遍历词典列表

[英]loop through list of dictionaries

我有一个词典列表。 列表中有几个点,有些是多个点。 当存在多个条目时,我想计算该点的x和y的平均值。 我的问题是,我不知道如何遍历字典列表来比较点的ID!

当我使用这样的东西时:

for i in list:
  for j in list:
    if i['id'] == j['id']:
      point = getPoint(i['geom'])
      ....

抱歉,格式化有点棘手......第二个循环在第一个循环中......我认为它比较了列表的第一个条目,所以它是相同的...所以我必须从第二个循环开始与第二个条目,但我不能用i-1做到这一点,因为我是孔词典...有人的想法? 提前致谢!

 for j in range(1, len(NEWPoint)):
      if i['gid']==j['gid']:
         allsamePoints.append(j)
      for k in allsamePoints:
         for l in range(1, len(allsamePoints)):
            if k['gid']==l['gid']:
                Point1 = k['geom']
                Point2=l['geom']
                X=(Point1.x()+Point2.x())/2
                Y=(Point1.y()+Point2.y())/2
                AVPoint = QgsPoint(X, Y)
                NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
                del l
      for m in NEWReturnList:
          for n in range(1, len(NEWReturnList)):
              if m['gid']==n['gid']:
                 Point1 = m['geom']
                 Point2=n['geom']
                 X=(Point1.x()+Point2.x())/2
                 Y=(Point1.y()+Point2.y())/2
                 AVPoint = QgsPoint(X, Y)
                 NEWReturnList.append({'gid': j['gid'], 'geom': AVPoint})
                 del n
              else:
                 pass

好吧,我想...此刻更令人困惑:))...

一种方法是改变你存储积分的方式,因为正如你已经注意到的那样,很难从中得到你想要的东西。

一个更有用的结构是一个dict,其中id映射到一个点列表:

from collections import defaultdict
points_dict = defaultdict(list)

# make the new dict
for point in point_list:
    id = point["id"]
    points_dict[id].append(point['geom'])

def avg( lst ):
    """ average of a `lst` """
    return 1.0 * sum(lst)/len(lst)

# now its simple to get the average
for id in points_dict:
    print id, avg( points_dict[id] )

我不完全确定你想做什么,但我认为列表过滤会对你有帮助。 有内置的函数filter ,它迭代序列,并为每个项调用用户定义的函数,以确定是否在结果列表中包含该项。

例如:

def is4(number):
   return number == 4

l = [1, 2, 3, 4, 5, 6, 4, 7, 8, 4, 4]
filter(is4, l) # returns [4, 4, 4, 4]

因此,有了一个字典列表,过滤掉所有具有等于给定值的条目的字典,你可以这样做:

def filter_dicts(dicts, entry, value):
   def filter_function(d):
      if entry not in d:
         return False
      return d[entry] == value
   return filter(filter_function, dicts)

使用此函数,要获取“id”条目等于2的所有词典,您可以执行以下操作:

result = filter_dicts(your_list, "id", 2)

有了这个,你的主循环看起来像这样:

processed_ids = set()
for item in list:
   id = item['id']
   if id in processed_ids:
      continue
   processed_ids.add(id)
   same_ids = filter_dicts(list, "id", id)
   # now do something with same_ids

我希望我能正确理解你,这对你很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM