我想在存储计数器的字典中添加一个值:
d[key] += 1
Run Code Online (Sandbox Code Playgroud)
但有时钥匙还不存在.检查密钥是否存在似乎太难看了.是否有一个漂亮的pythonic单线程 - 如果密钥存在则添加,或者1如果密钥不在dict.keys中则创建值?
谢谢
您可以使用collections.Counter- 这保证了所有值都是1或更多,支持各种初始化方式,并支持某些其他有用的功能dict/defaultdict不支持:
from collections import Counter
values = ['a', 'b', 'a', 'c']
# Take an iterable and automatically produce key/value count
counts = Counter(values)
# Counter({'a': 2, 'c': 1, 'b': 1})
print counts['a'] # 2
print counts['d'] # 0
# Note that `counts` doesn't have `0` as an entry value like a `defaultdict` would
# a `dict` would cause a `KeyError` exception
# Counter({'a': 2, 'c': 1, 'b': 1})
# Manually update if finer control is required
counts = Counter()
for value in values:
counts.update(value) # or use counts[value] += 1
# Counter({'a': 2, 'c': 1, 'b': 1})
Run Code Online (Sandbox Code Playgroud)
您可以使用
d={}
key='sundar'
d[key]=d.get(key,0)+1
print d
#output {'sundar': 1}
d[key]=d.get(key,0)+1
print d
#output {'sundar': 2}
Run Code Online (Sandbox Code Playgroud)
>>> import collections
>>> d = collections.defaultdict(int)
>>> key = 'foo'
>>> d[key] += 1
>>> d
defaultdict(<type 'int'>, {'foo': 1})
>>> d[key]
1
>>> d[key] += 1
>>> d[key]
2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3087 次 |
| 最近记录: |