1 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個贊
查看您的輸入數(shù)據(jù),它是這樣的: userId 1, id 1 has 0 true, and 3 false userId 1, id 2 has 1 true, and 1 false
給定所需的輸出,看起來你真的想使用id而不是userId在你的查找中。id除此之外,第一次在生成的字典中插入時,會出現(xiàn)會計(jì)問題。我會這樣修復(fù)它:
todos_by_user_true = {}
todos_by_user_false = {}
# Increment complete TODOs count for each user.
for todo in todos:
if todo["completed"]==True:
try:
# Increment the existing user's count.
todos_by_user_true[todo["id"]] += 1
except KeyError:
# This user has not been seen. Set their count to 1.
todos_by_user_true[todo["id"]] = 1
elif todo["completed"]==False:
try:
# Increment the existing user's count.
todos_by_user_false[todo["id"]] += 1
except KeyError:
# This user has not been seen. Set their count to 1.
todos_by_user_false[todo["id"]] = 1
其中(順便說一句)已經(jīng)是您的評論中的內(nèi)容。
就個人而言,我會在插入之前檢查字典中的鍵,而不是使用try..except,如下所示:
todos_by_user_true = {}
todos_by_user_false = {}
# Increment complete TODOs count for each user.
for todo in todos:
key = todo["id"]
if todo["completed"]: # true case
# If `id` not there yet, insert it to 0
if key not in todos_by_user_true:
todos_by_user_true[key] = 0
# increment
todos_by_user_true[key] += 1
else: # false case
# If `id` not there yet, insert it to 0
if key not in todos_by_user_false:
todos_by_user_false[key] = 0
# increment
todos_by_user_false[key] += 1
這給出了:
todos_by_user_true = {2:1}
todos_by_user_false = {1:3,2:1}
邏輯是這樣的,你不能有: todos_by_user_true = {1:0}
當(dāng)你找到它時,你就計(jì)算它的價值;而不是id從單獨(dú)的列表中迭代。
添加回答
舉報(bào)