【发布时间】:2017-09-21 21:03:40
【问题描述】:
所以我有一个函数count_by_type(db, stype),我必须计算存在多少具有与 stype 匹配的类型的单类型和双类型口袋妖怪,对它们进行计数,然后将其汇总为一个 int。
给定一个名为 db 的字典,格式如下:
sample_db = {
"Bulbasaur": (1, "Grass", "Poison", 45, 49, 49, 45, 1, False),
"Charmander": (4, "Fire", None, 39, 52, 43, 65, 1, False),
"Charizard": (6, "Fire", "Flying", 78, 84, 78,100, 1, False),
"Moltres": (146, "Fire", "Flying", 90,100, 90, 90, 1, True),
"Crobat": (169, "Poison", "Flying", 85, 90, 80,130, 2, False),
"Tornadus, (Incarnate Form)": (641, "Flying", None, 79,115, 70,111, 5, True),
"Reshiram": (643, "Dragon", "Fire", 100,120,100, 90, 5, True)
}
我实现了一些代码来完成上述操作。这里:
def count_by_type(db, stype):
single_type_count = 0
dual_type_count = 0
total_count = 0
for pokemon in db:
if (db[pokemon][1] == stype and db[pokemon][2] != stype) or (db[pokemon][1] != stype and db[pokemon][2] == stype):
single_type_count += 1
if (db[pokemon][1]== stype or db[pokemon][2] == stype):
dual_type_count += 1
total_count = single_type_count + dual_type_count
return total_count
问题是它返回一个像 (1,2,3) 或 (4,0,4) 这样的集合,而不是添加计数器,因此它会分别返回 6 或 8。
编辑:实际上我返回了一个整数,我需要以与集合表示法匹配的方式返回值。对此感到抱歉。
【问题讨论】:
标签: python dictionary for-loop sum tuples