1 回答
TA贡献1806条经验 获得超5个赞
查看您的输入数据,它是这样的: userId 1, id 1 has 0 true, and 3 false userId 1, id 2 has 1 true, and 1 false
给定所需的输出,看起来你真的想使用id而不是userId在你的查找中。id除此之外,第一次在生成的字典中插入时,会出现会计问题。我会这样修复它:
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
其中(顺便说一句)已经是您的评论中的内容。
就个人而言,我会在插入之前检查字典中的键,而不是使用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}
当你找到它时,你就计算它的价值;而不是id从单独的列表中迭代。
添加回答
举报
