Python-如何比较字典上循环每次迭代时更改的值?

Python-如何比较字典上循环每次迭代时更改的值?,python,python-3.x,dictionary,counter,Python,Python 3.x,Dictionary,Counter,给定一个字典(db)和字符串(type),my函数需要搜索整个字典,并找到所有以字符串(type)作为其唯一类型的项,找到所有类型为其类型的1/2的项,然后将这两个值相加。然后它必须返回统计数据的元组 我被如何跟踪计数器和函数返回不正确的元组所困扰。我想我的结构可能很好,但我知道它工作不正常。我怎样才能解决这个问题?什么能帮我跟踪柜台?我对if语句的问题是否检查不正确 这是我目前的代码: def count_by_type(db,type): only_type=0 half_t

给定一个字典(db)和字符串(type),my函数需要搜索整个字典,并找到所有以字符串(type)作为其唯一类型的项,找到所有类型为其类型的1/2的项,然后将这两个值相加。然后它必须返回统计数据的元组

我被如何跟踪计数器和函数返回不正确的元组所困扰。我想我的结构可能很好,但我知道它工作不正常。我怎样才能解决这个问题?什么能帮我跟踪柜台?我对if语句的问题是否检查不正确

这是我目前的代码:

def count_by_type(db,type):
    only_type=0
    half_type=0
    for key, values in db.item():
        if type in values[1] or values[2]:
            half_type+=1
        if type in (values[1] or values[2]) and (values[1] or values[2]==None:)
            only_type+=1
    my_sum=half_type+ only_type
    return (only_type, half_type, my_sum)
以下是预期输入/输出的示例:

db={'bulb':(1,'Grass','poison', 1, False), 
    'Char':(4, 'poison','none', 1, False)}

types='poison'

'char' has poison as its only type, only_type+=1
'bulb' has poison as 1/2 of its types, half_type +=1
my_sum=2
return: (1,1,2)

代码中存在一些语法问题,导致逻辑的计算结果与预期不符。这是正确的代码

代码:

def count_by_type(the_db, the_type):
    only_type = 0
    half_type = 0
    for values in the_db.values():
        if the_type in (values[1], values[2]):
            if None in (values[1], values[2]):
                only_type += 1
            else:
                half_type += 1

    return only_type, half_type, half_type + only_type
db = {
    'bulb': (1,'Grass', 'poison', 1, False),
    'Char': (4, 'poison', None, 1, False)
}

print(count_by_type(db, 'poison'))
(1, 1, 2)
测试代码:

def count_by_type(the_db, the_type):
    only_type = 0
    half_type = 0
    for values in the_db.values():
        if the_type in (values[1], values[2]):
            if None in (values[1], values[2]):
                only_type += 1
            else:
                half_type += 1

    return only_type, half_type, half_type + only_type
db = {
    'bulb': (1,'Grass', 'poison', 1, False),
    'Char': (4, 'poison', None, 1, False)
}

print(count_by_type(db, 'poison'))
(1, 1, 2)
结果:

def count_by_type(the_db, the_type):
    only_type = 0
    half_type = 0
    for values in the_db.values():
        if the_type in (values[1], values[2]):
            if None in (values[1], values[2]):
                only_type += 1
            else:
                half_type += 1

    return only_type, half_type, half_type + only_type
db = {
    'bulb': (1,'Grass', 'poison', 1, False),
    'Char': (4, 'poison', None, 1, False)
}

print(count_by_type(db, 'poison'))
(1, 1, 2)

对于键,db.item()中的值:
不能为。如果键入值[1]或值[2]::您不想写入它,那么它也是
items()。这可能是您的问题:
如果键入值[1]或键入值[2]:
我编写了值作为或,因为其中可能没有一种类型,但也可能不是,我不知道如何检查它@Jean-François Fabreno一个解决方案,但值得一提的是,使用切片进行比较,在
中使用
搭配使用,这将更有意义,并为您节省一些宽度切片如何?我能理解和或,但我该如何切分呢?