好的,我最近剛剛在候選人和計算與每個候選人的id相匹配的票數方面得到了幫助。我現在遇到的問題是,我想逐一回圈每個json陣列列,以表示第一選擇、第二選擇,以此類推。因此,是否有辦法回圈每個json陣列列,將其作為一個回合,同時計算每回合的票數以匹配每個候選人。
main.py
import json
import collections
import numpy as np
with open('data.json', 'r') as f.
db = json.load(f)
# 準備一個包含所有候選人資訊的臨時結構,并初始化票數。
candidates_dict = {}
for candidate in db["cates"]:
candidates_dict[candid["id"]] = {"name": candidate["name"], "num_votes": 0}.
# loop on votes lists and count votes for all candidates。
for votes in db["votes"] 。
for candidate_id in votes:
candidates_dict[candid]["num_votes"] =1
# 只需列印每個候選人做了多少票即可
for candidate_id, candidate_info in candidates_dict.items()。
print ("候選人{}有{}票"。 format(candidate_info["name"], candidate_info["num_votes"] )
data.json
{}。
"候選人": []。
{
"id": 1,
"name": "Stan",
"status": true
},
{>
"id": 2,
"name": "Avia",
"status": true
},
{>
"id": 3,
"name": "Bob",
"status": true
}
],
" votes": []。
[1, 2。 3],
[2,/span> 1。 3],
[1]/span>,
[2, 3] ,
[3, 1] ,
[/span>3。 2, 1]
]
}
uj5u.com熱心網友回復:
這是你想要的嗎?
data = {
"candors": [
{
"id": 1,
"name": "Stan",
"狀態": True。
},
{
"id": 2,
"name": "阿維亞",
"狀態": True。
},
{
"id": 3,
"name": "Bob",
"狀態": True。
}
],
"票數": ["票數": ["票數"].
[1, 2, 3]。
[2, 1, 3] 。
[1]。
[2, 3]。
[3, 1]。
[3, 2, 1] 。
]
}
from itertools import zip_longest
votes_columns = data["votes"]
for rank, *votes in zip_longest(range(3), *votes_columns) 。
print(f "for rank {rank}, votes are {votes}"/span>)
for rank 0, votes are [1, 2, 1, 2, 3, 3]
for rank 1, votes are [ 2, 1, None, 3, 1, 2]
for rank 2, votes are [3, 3。None, None, None, 1]
uj5u.com熱心網友回復:
根據我的理解,我做了這個
。
for votes in db["votes"] 。
for round_, candidate_id in enumerate(vots):
candidates_dict[candid]["num_votes"] =1。
if 'rounds' not in candidates_dict[candid] 。
candidates_dict[candid]['rounds'] = {1: 0, 2:0, 3:0}。
candidates_dict[candid]['rounds'][round_ 1] = 1]
for c_id, c_dict in candidates_dict.items()。
print(c_id, c_dict['rounds'/span>])
>>>1 {1: 2, 2: 2, 3: 1}。
>>>2 {1: 2, 2: 2, 3: 0}。
>>>3 {1: 2, 2: 1, 3: 2}。
但是我看到你匯入了numpy,所以也許你要檢查這個問題。將Python序列轉換為NumPy陣列,填補缺失值
這將幫助你以不同的方式獲得你的資料 "列"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/306905.html
標籤:
上一篇:一般問題--在小于O(N^2)的時間內找到陣列中可能的配對。
下一篇:<p>我有兩個陣列,一個是selectedOption,另一個是defaultOption,如果selectedOptionid出現在defaultOption陣列的任何一個選項屬性中,那
