Python- 如何比较随着字典循环的每次迭代而变化的值?
Python- how to compare values that change with each iteration of loop on dictionary?
给定一个字典 (db) 和一个字符串 (type),我的函数需要搜索整个字典并找到所有以 string(type) 作为唯一类型的项目,找到所有类型为 1/ 的项目2 种类型,并对这两个值求和。然后它必须 return 统计的元组。
我对如何跟踪计数器挂断了,函数是 returning 不正确的元组。我认为我的结构可能是合理的,但我知道它不能正常工作。我怎样才能解决这个问题?什么可以帮助我跟踪柜台?我的问题是 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)
这是预期的示例 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)
您的代码中存在一些语法问题,导致逻辑无法按预期进行评估。这是更正后的代码。
代码:
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) 和一个字符串 (type),我的函数需要搜索整个字典并找到所有以 string(type) 作为唯一类型的项目,找到所有类型为 1/ 的项目2 种类型,并对这两个值求和。然后它必须 return 统计的元组。
我对如何跟踪计数器挂断了,函数是 returning 不正确的元组。我认为我的结构可能是合理的,但我知道它不能正常工作。我怎样才能解决这个问题?什么可以帮助我跟踪柜台?我的问题是 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)
这是预期的示例 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)
您的代码中存在一些语法问题,导致逻辑无法按预期进行评估。这是更正后的代码。
代码:
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)