【问题标题】:Dictionary value not updating as expected when using -=使用 -= 时字典值未按预期更新
【发布时间】:2019-01-17 04:52:26
【问题描述】:

我有一本字典和一个词:

check = {'a': 3, 'e': 1, 'p': 2, 'r': 1, 'u': 1, 't': 1}
word = 'rapturerererer'

如果来自word 的所有字母都在check 中,我正在寻找运行测试。所以我需要对所有用完的字母进行计数,并检查最后是否有负数。

我有代码,但它总是将值限制在 0 并且从不返回负值:

for letter in word:
    if check.get(letter):
        check[letter] -= 1
print(check)

{'a': 2, 'p': 1, 'r': 0, 'e': 0, 't': 0, 'u': 0}

我期待的是这样的:

{'a': 2, 'p': 1, 'r': -5, 'e': -4, 't': 0, 'u': 0}

谁能解释为什么这些值在 0 处停止?

【问题讨论】:

  • if 0 计算结果为 False - 将条件更改为 if check.get(letter) is not None

标签: python string python-2.7 dictionary counter


【解决方案1】:

您的错误发生是因为检查 if d.get(x) 评估值的性质(即它是 0 还是类似 False)而不是只是密钥的存在。

另一种方法是使用collections.Counter 后跟字典理解:

from collections import Counter

check = {'a': 3, 'e': 1, 'p': 2, 'r': 1, 'u': 1, 't': 1}
word = 'rapturerererer'

word_count = Counter(word)

res = {k: check[k] - word_count[k] for k in check}

print(res)

{'a': 2, 'e': -3, 'p': 1, 'r': -5, 'u': 0, 't': 0}

这将起作用,因为Counter 对象为尚未添加的键返回 0 值。

【讨论】:

    【解决方案2】:
    if check.get(letter):
        check[letter] -= 1
    

    if check.get(letter) 不仅会在letter 丢失时失败;如果字典中的值为"falsy",它也会失败。 None 是假的,0 也是如此。一旦达到0,测试就会失败,不会再发生递减。

    请改用in

    if letter in check:
        check[letter] -= 1
    

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 2018-03-03
      • 2021-07-03
      • 2021-11-22
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多