[英]Pythonically adding keys to a dict
I want to add a key with a count one and increment it everytime it increases, this is a classic operation. 我想添加一个带有计数的键,并在每次增加时递增它,这是一个经典的操作。 This is my regular code.
这是我的常规代码。
d = OrderedDict()
for i, v in enumerate(s):
if v not in d:
d[v] = 1
else:
d[v] += 1
How can I do this with 1 line of code using setdefault
and not collections. Counter
如何使用
setdefault
而不是collections. Counter
使用1行代码执行此操作collections. Counter
collections. Counter
Like if this was a list then I could have done, collections. Counter
如果这是一个列表然后我可以做到,
d.setdefault(v, []).append()
Is there a way to do a similar thing with integer addition. 有没有办法用整数加法做类似的事情。
你可以这样做:
d[v] = d.get(v, 0) + 1
Just use an ordered counter. 只需使用有序的计数器。 If you are happy to import
OrderedDict
, there's no reason, in my opinion, you should avoid Counter
. 如果您乐意导入
OrderedDict
,我认为没有理由避免使用Counter
。
from collections import OrderedDict, Counter
class OrderedCounter(Counter, OrderedDict):
pass
s = [3, 1, 3, 1, 2, 3, 4]
d = OrderedCounter(s)
print(d)
OrderedCounter({3: 3, 1: 2, 2: 1, 4: 1})
Note in Python 3.7+ you can just use Counter
since dictionaries are insertion-ordered. 请注意,在Python 3.7+中,您可以使用
Counter
因为字典是按插入顺序排列的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.