简体   繁体   English

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

[英]Python- how to compare values that change with each iteration of loop on dictionary?

Given a dictionary (db) and string (type), my function needs to search through the whole dictionary and find all items that have string(type) as their ONLY type, find all items that have type as 1/2 of their types, and sums the two values. 给定一个字典(db)和字符串(type),我的函数需要搜索整个字典,并找到所有以string(type)作为其唯一类型的项目,找到所有类型为其类型1/2的项目,并将两个值相加。 Then it must return the tuple of the statistics. 然后,它必须返回统计信息的元组。

I'm hung up on how to keep track of the counter and the function is returning incorrect tuples. 我挂了如何跟踪计数器,该函数返回不正确的元组。 I think my structure may be sound but I know it's not working properly. 我认为我的结构听起来不错,但我知道它无法正常工作。 How can I fix this? 我怎样才能解决这个问题? What will help me keep track of the counter? 什么可以帮助我跟踪柜台? Is my issue with the if statements not checking correctly? 我的if语句问题不能正确检查吗?

Here is my current code: 这是我当前的代码:

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)

Here is an example of expected input/output: 这是预期输入/输出的示例:

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)

There were a few syntax issues in your code that were causing the logic to not evaluate as you expected. 您的代码中存在一些语法问题,这些问题导致逻辑无法按预期进行评估。 Here is corrected code. 这是更正的代码。

Code: 码:

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

Test Code: 测试代码:

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

print(count_by_type(db, 'poison'))

Results: 结果:

(1, 1, 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM