我需要帮助找出解决我问题的办法。我目前正在尝试创建一个选举系统,该系统将解析JSON数据并输出我输入的选举的结果。问题是,我可以弄清楚如何让python将一个整数(候选人的id )与候选人的名字匹配,这样我就可以将它计算为他们的选票。
此外,如果你能帮助我如何使它计数的选票,这将是非常有帮助的。
main.py
import json
from collections import Counter
import numpy as np
with open('data.json', 'r') as f:
db = json.load(f)
for candidate in db["candidates"]:
ids = dict()
idc = candidate["id"]
name = candidate["name"]
status = candidate["status"]
ids[idc] = name
dids = ids[idc]
if dids == name:
print(ids)
for vote in db["votes"]:
raw = dict()
r = vote[0]
raw[idc] = vote[0]
print(raw[idc])
x = 0
c = Counter(vote[0])
print ('Candidate {} has {} votes'.format(x, c[x]))data.json
{
"candidates": [
{
"id": 1,
"name": "Avia",
"status": true
},
{
"id": 2,
"name": "Stan",
"status": true
},
{
"id": 3,
"name": "Bob",
"status": true
}
],
"votes": [
[1, 2, 3],
[2, 1, 3],
[1],
[2, 3],
[3, 1],
[3, 2, 1]
]
}发布于 2021-09-14 13:43:36
如果@Giordano是正确的,请从每个id的选票数开始:
votes_list = sum(db['votes'], []) # this trick flattens the nested lists
votes_count = {key: votes_list.count(key) for key in set(votes_list)}这给出了一个与每个id的总票数不一致的情况:
{1: 5, 2: 4, 3: 5}然后将结果映射到候选人:
candidates = db["candidates"]
for candidate in candidates:
candidate["votes"] = votes_count.get(candidate["id"], 0)这就给出了每个候选人的选票:
>>> candidates
[{'id': 1, 'name': 'Avia', 'status': True, 'votes': 5},
{'id': 2, 'name': 'Stan', 'status': True, 'votes': 4},
{'id': 3, 'name': 'Bob', 'status': True, 'votes': 5}]最后,将候选人按票数降序排序:
sorted(candidates, key=lambda k: -k['votes'])发布于 2021-09-14 13:58:10
我从你的问题中得到的是,你只需要显示哪个候选人获得了多少选票。如果我的解释是正确的,那么下面是其中一种方法:
import json
from collections import defaultdict
import numpy as np
db = {
"candidates": [
{
"id": 1,
"name": "Avia",
"status": 'true'
},
{
"id": 2,
"name": "Stan",
"status": 'true'
},
{
"id": 3,
"name": "Bob",
"status": 'true'
}
],
"votes": [
[1, 2, 3],
[2, 1, 3],
[1],
[2, 3],
[3, 1],
[3, 2, 1]
]
}
count_data = defaultdict(int)
for vote in db["votes"]:
for data in vote:
count_data[data] += 1
for data in db['candidates']:
print ('Candidate '+data['name']+' has got '+str(count_data[data['id']])+' votes')输出:
Candidate Avia has got 5 votes
Candidate Stan has got 4 votes
Candidate Bob has got 5 votes请注意:在这里,我没有像您所做的那样从文件中读取数据,您可以相应地更新此代码以从文件中读取数据,但是核心逻辑保持不变。
发布于 2021-09-14 14:00:17
约斯特的回答是正确的。
我只想提出另一个临时结构的答案。
(说明载于评论中)
with open('data.json', 'r') as f:
db = json.load(f)
# prepare a temporary structure with all the candidates info + initialize number of votes
candidates_dict = {}
for candidate in db["candidates"]:
candidates_dict[candidate["id"]] = {"name": candidate["name"], "num_votes": 0}
# loop on votes lists and count votes for all candidates
for votes in d["votes"]:
for candidate_id in votes:
candidates_dict[candidate_id]["num_votes"] += 1
# just print how many votes each candidate has done
for candidate_id, candidate_info in candidates_dict.iteritems():
print "candidate {} has {} votes".format(candidate_info["name"], candidate_info["num_votes"])输出:
candidate Avia has 5 votes
candidate Stan has 4 votes
candidate Bob has 5 voteshttps://stackoverflow.com/questions/69178776
复制相似问题