【问题标题】:Function is returning a set of ints instead of adding the ints函数返回一组整数而不是添加整数
【发布时间】: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


    【解决方案1】:

    我自己解决了这个愚蠢的错误:你所要做的就是创建一个变量并将其设置为一个元组。所以在这种情况下,它将是 totaltuple = ((single_type_count, dual_type_count, total_count)

    【讨论】:

      猜你喜欢
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多