Python 循环浏览字典列表
我有一份字典清单。列表中有几个点,有些是多个点。当有多重输入时,我想计算这个点的x和y的平均值。我的问题是,我不知道如何循环使用字典列表来比较点的ID 当我使用这样的东西时:Python 循环浏览字典列表,python,loops,dictionary,Python,Loops,Dictionary,我有一份字典清单。列表中有几个点,有些是多个点。当有多重输入时,我想计算这个点的x和y的平均值。我的问题是,我不知道如何循环使用字典列表来比较点的ID 当我使用这样的东西时: for i in list: for j in list: if i['id'] == j['id']: point = getPoint(i['geom']) .... 抱歉,格式化有点棘手。。。第二个循环在第一个循环内。。。 我认为它比较了列表的第一个条目,所以它是相同的。。。所以
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] )
一种方法是改变你存储积分的方式,因为你已经注意到,很难从中得到你想要的东西 一个更有用的结构是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)
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
使用此函数,要获取“id”项等于2的所有词典,可以执行以下操作:
result = filter_dicts(your_list, "id", 2)
这样,您的主循环可以如下所示:
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)
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
我希望我正确地理解了您的意思,这对您很有帮助。我不完全确定您想做什么,但我认为列表筛选会对您有所帮助。有一个内置函数
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)
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
使用此函数,要获取“id”项等于2的所有词典,可以执行以下操作:
result = filter_dicts(your_list, "id", 2)
这样,您的主循环可以如下所示:
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)
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
我希望我正确地理解了您的意思,这对您很有帮助。如果三个或更多的元素具有相同的
“id”
,该怎么办?是否要计算每对元素的平均值?还是要将具有相同'id'
的所有元素进行聚类并取聚类的平均值?仍然不清楚。你能给出样本输入和预期输出吗?你为什么要取i-1?您仍然循环使用所有可能的匹配项。请不要将列表
用作变量名。发布数据外观示例以及您希望从中获得的示例也很有帮助。很多时候,我们都在寻找错误问题的正确答案。最好的办法是说,“这就是我拥有的……这就是我想要的……这就是我正在做的……”。编写代码需要更长的时间,但它会迫使您考虑您的算法,并且它为我们提供了更大的回答灵活性。如果三个或更多元素具有相同的'id'
,会发生什么情况?是否要计算每对元素的平均值?还是要将具有相同'id'
的所有元素进行聚类并取聚类的平均值?仍然不清楚。你能给出样本输入和预期输出吗?你为什么要取i-1?您仍然循环使用所有可能的匹配项。请不要将列表
用作变量名。发布数据外观示例以及您希望从中获得的示例也很有帮助。很多时候,我们都在寻找错误问题的正确答案。最好的办法是说,“这就是我拥有的……这就是我想要的……这就是我正在做的……”。写作需要更长的时间,但是它迫使你思考你的算法,它给我们提供了更多的灵活性。我们在THC4K是正确的时候收回了我在写作中间的评论。一个dict列表一点也不理想——更自然的是,您有一个dict,您可以首先在其中消除重复数据+1但是,THC4k,如果您添加了关于如何从列表中构建这样一个dict的代码,以使OP更清晰,那就太好了。因此,当我使用points_dict[id]。append(…)时,我得到了一个包含多个具有不同id和几何体的项的字典?!我想用字典列表来实现这一点,因为我找不到任何东西可以在字典中存储多个项目(如excel表格中的项目)…注意defaultdict(list)
使用内置的list
这就是为什么你永远不应该对变量名使用list
字典是从任何(可散列)映射而来的类型转换为任何类型的数据。规范字典将字符串映射到字符串(dict[“spam”]=“ham”
),但这不是唯一可以做的事情。在这种情况下,THC4k将一个字符串(点的id
)映射到具有这些id
s的点的列表。collections.defaultdict
意味着我们尚未处理的字符串映射到[]
。好的,我将有一个id条目和几个点几何体。。。嗯,我想我必须找到另一个解决方案,因为点本身的计算已经花费了很多时间。。。它们被存储到字典列表中。。。因此,我必须更改计算,否则我将在计算期间将这些点存储到字典列表中,然后将其转换为字典。。。。那不是很聪明。