这基本上就是我试图做的,这是行不通的.有没有办法找出字典的值并进行数学化?为了废话的例子:
dictionaryNumbers = {'a':10,'b':10,'c':1,'d':1,'e':5,'f':1}
dictionaryNumbers['a'] += 5
#The goal would be dictionaryNumbers['a'] would equal 15.
Run Code Online (Sandbox Code Playgroud)
编辑:
伙计们感谢您的反馈.似乎我在调用函数来修改集合的顺序存在缺陷.我在数学发生之前打印输出.再次感谢.
你大部分都做对了,你的代码运行正常:
>>> dictionaryNumbers = {'a':10,'b':10,'c':1,'d':1,'e':5,'f':1}
>>> dictionaryNumbers['a'] += 5
>>> dictionaryNumbers['a']
15
Run Code Online (Sandbox Code Playgroud)
但是对于还没有在dict中的任何键,你必须先测试(if key not in dictionaryNumbers)或使用.get():
>>> dictionaryNumbers['z'] = dictionaryNumbers.get('z', 0) + 3
Run Code Online (Sandbox Code Playgroud)
哪个变老了.
但我会改用一个collections.Counter()班级:
>>> from collections import Counter
>>> counter = Counter()
>>> counter.update({'a':10,'b':10,'c':1,'d':1,'e':5,'f':1})
>>> counter
Counter({'a': 10, 'b': 10, 'e': 5, 'c': 1, 'd': 1, 'f': 1})
>>> counter['a'] += 5
>>> counter['a']
15
>>> counter.most_common(3)
[('a', 15), ('b', 10), ('e', 5)]
Run Code Online (Sandbox Code Playgroud)
好处:
Counter(items_to_count).counter1 + counter2返回一个新的Counter,所有值相加.