如果我有一个字符串'abc'和一个字典{'a':1, 'b':1, 'c':0},并且只有当该字符串的所有元素都是字典中的值,并且所有键的值都> 0时,我才想执行一些操作,那么如何测试它呢?
我有一个循环:
def f(adic, astring):
for i in astring:
if i in adic.keys() and adic[i] > 0:
adic[i] -= 1
return adic以及函数中的输入
f({'a': 1, 'i': 3, 'h': 1, 'r': 1, 't': 1, 'y': 2}, "hair")我得到了预期的输出:
{'a': 0, 'i': 2, 'h': 0, 'r': 0, 't': 1, 'y': 2}但是,如果我用相同的输出再次测试它,就会得到以下结果:
{'a': 0, 'i': 1, 'h': 0, 'r': 0, 't': 1, 'y': 2}我期待着得到这个:
{'a': 0, 'y': 2, 'r': 0, 't': 1, 'i': 2, 'h': 0}因为只有当字符串的所有元素都出现在字典中,并且当前的值不等于0时,我才想执行此操作。
发布于 2014-08-07 10:02:28
您实际上是在检查每个字母之后直接执行递减操作,但是您想要做的(如果我做得对)是首先检查字典中是否出现了字符串的所有元素(不管您说了什么,您没有对一个列表进行操作),并且大于0,然后执行递减操作。
所以,一个可能的解决办法可能是这样的(
def f(hand, word):
# check first whether all conditions are fulfilled,
# return hand unmodified if not
for i in word:
if i not in hand.keys():
return hand
if hand[i] <= 0:
return hand
# if conditions are fulfilled, do the decrementation
for i in word:
hand[i] -= 1
return handhttps://stackoverflow.com/questions/25179233
复制相似问题