在正确的位置获取正确的数据
Posted
技术标签:
【中文标题】在正确的位置获取正确的数据【英文标题】:Get the right data at the right place 【发布时间】:2022-01-20 09:37:06 【问题描述】:我有一个 Json 文件,并且能够从中提取一些值并将它们汇总。我希望能够将结果放在正确的键上,但无法弄清楚。 以下是我的代码:
from builtins import print
import json
import jmespath
from collections import Counter
const = ['constituency A','constituency B','constituency C']
region = ['region A','region B','reigon C']
poll = ['POLLING STATION A','POLLING STATION B','POLLING STATION C','POLLING STATION Z','POLLING STATION F']
fake = 'transaction':['region A':'constituency A':
'POLLING STATION A':'PARTY A':10,'PARTY B':20,'PARTY C':30,'PARTY D':40,
'POLLING STATION Z':'PARTY A':50,'PARTY B':60,'PARTY C':70,'PARTY D':80,
'POLLING STATION B':'PARTY A':90,'PARTY B':100,'PARTY C':110,'PARTY D':120,
'POLLING STATION F':'PARTY A':190,'PARTY B':1100,'PARTY C':1110,'PARTY D':1120,,
]
a = json.dumps((fake))
p = json.loads(a)
j = jmespath.search('transaction[*]',p)
ham = []
man = set()
for new_d in j:
for k,v in new_d.items():
for i_k,i_v in v.items():
for w,c in i_v.items():
if w in poll and i_k in const and k in region:
ham.append(c)
up = len(ham)
i= 0
a1=Counter()
while i < up:
a1 += Counter(ham[i])
i+=1
print(a1)
所以这就是我想要做的,结果是 a1 将被这样放置一个字典 =>[ 'region A':'constituency A':'PARTY D': 1360, 'PARTY C': 1320, 'PARTY B': 1280, 'PARTY A': 340]
当同时计算A区选区B的投票时,结果会以选区B为key添加到A区。
【问题讨论】:
【参考方案1】:我已经迭代了每个字典并计算了每个选区的党派票数。
fake =
'transaction': [
'region A':
'constituency A':
'POLLING STATION A':
'PARTY A': 10, 'PARTY B': 20, 'PARTY C': 30, 'PARTY D': 40,
'POLLING STATION Z':
'PARTY A': 50, 'PARTY B': 60, 'PARTY C': 70, 'PARTY D': 80,
'POLLING STATION B':
'PARTY A': 90, 'PARTY B': 100, 'PARTY C': 110, 'PARTY D': 120,
'POLLING STATION F':
'PARTY A': 190, 'PARTY B': 1100, 'PARTY C': 1110, 'PARTY D': 1120,
,
]
data = fake['transaction'][0]
total_result =
for region, constituencies in data.items():
total_result[region] =
for constituency, stations in constituencies.items():
party_votes =
for station, parties in stations.items():
for party, vote in parties.items():
party_votes[party] = party_votes.get(party, 0) + vote
total_result[region][constituency] = party_votes
print(total_result)
打印
'region A': 'constituency A': 'PARTY A': 340, 'PARTY B': 1280, 'PARTY C': 1320, 'PARTY D': 1360
【讨论】:
感谢 Eduardo,您的解决方案很有帮助。以上是关于在正确的位置获取正确的数据的主要内容,如果未能解决你的问题,请参考以下文章
微信小程序正确的异步request请求,根据经纬度获取地理位置信息
「RecyclerView中的位置」你真的会正确获取Item的位置么?