更好的写法 'assign A or if not possible - B'

Better way to write 'assign A or if not possible - B'

所以,在我的代码中,我有一本字典,我用它来计算我事先不知道的项目:

if a_thing not in my_dict:
    my_dict[a_thing] = 0
else:
    my_dict[a_thing] += 1

显然,我无法增加尚不存在的值的条目。出于某种原因,我有一种感觉(在我仍然-Python-缺乏经验的大脑中)可能存在更 Pythonic 的方式来做到这一点,比如说,一些允许分配结果的结构对事物的表达,如果不可能的话,对其他事物的表达 在单个语句中

那么,Python 中是否存在类似的东西?

对于 defaultdictcollections 这看起来是个不错的工作。观察下面的例子:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['a'] += 1
>>> d
defaultdict(<class 'int'>, {'a': 1})
>>> d['b'] += 1
>>> d['a'] += 1
>>> d
defaultdict(<class 'int'>, {'b': 1, 'a': 2})

defaultdict 将采用一个参数来指示您的初始值。在这种情况下,您要递增整数值,因此您需要 int.

或者,由于您正在计算项目,您也可以(如评论中所述)使用 Counter 最终将为您完成所有工作:

>>> d = Counter(['a', 'b', 'a', 'c', 'a', 'b', 'c'])
>>> d
Counter({'a': 3, 'c': 2, 'b': 2})

它还有一些不错的奖励。点赞most_common:

>>> d.most_common()
[('a', 3), ('c', 2), ('b', 2)]

现在你有一个订单给你最常见的计数。

使用get方法

>>> d = {}
>>> d['a'] = d.get('a', 0) + 1
>>> d
{'a': 1}
>>> d['b'] = d.get('b', 2) + 1
>>> d
{'b': 3, 'a': 1}