Python字典中的get方法

发布于 2024-11-30 13:47:32 字数 271 浏览 0 评论 0原文

所有,

我正在循环字典并计算出现的值。为此,我在另一个字典的赋值语句中使用 get 方法。这会返回语法错误“无法分配给函数调用”

counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
    counts(value[1]) = counts.get(value[1], 0) + 1

为什么分配会尝试指向函数而不是返回值?

All,

I'm looping over a dictionary and counting the values that occur. To do this, I'm using the get method in the assignment statement for another dictionary. This returns a syntax error "can't assign to function call"

counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
    counts(value[1]) = counts.get(value[1], 0) + 1

Why would the assignment try to point to the function, rather than the return value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

挽你眉间 2024-12-07 13:47:32
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
    counts[value[1]] = counts.get(value[1], 0) + 1

您需要方括号,而不是圆括号,才能从字典中获取项目。

另外,你这样做很困难。

from collections import defaultdict

# automatically start each count at zero
counts = defaultdict(int)
# we only need the values, not the keys
for value in mydict.itervalues(): 
    # add one to the count for this item
    counts[value[1]] += 1

或者

# only on Python 2.7 or newer
from collections import Counter

counts = Counter(value[1] for value in mydict.itervalues())
counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key,value in mydict.iteritems():
    counts[value[1]] = counts.get(value[1], 0) + 1

You need brackets, not parenthesis, to get an item from a dictionary.

Also, You're doing this the hard way.

from collections import defaultdict

# automatically start each count at zero
counts = defaultdict(int)
# we only need the values, not the keys
for value in mydict.itervalues(): 
    # add one to the count for this item
    counts[value[1]] += 1

or

# only on Python 2.7 or newer
from collections import Counter

counts = Counter(value[1] for value in mydict.itervalues())
情绪少女 2024-12-07 13:47:32

您需要的是 counts[value[1]] = ...,而不是 counts(value[1]) = ...

Instead of counts(value[1]) = ... you want counts[value[1]] = ....

反差帅 2024-12-07 13:47:32

将其更改

counts(value[1])

为:

counts[value[1]]

代码如下所示:

counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key, value in mydict.iteritems():
    counts[value[1]] = counts.get(value[1], 0) + 1

Change this:

counts(value[1])

to this:

counts[value[1]]

Code looks like this:

counts = {}
mydict = {'a':[1,2,5], 'b': [1,2,10]}
for key, value in mydict.iteritems():
    counts[value[1]] = counts.get(value[1], 0) + 1
青芜 2024-12-07 13:47:32
counts[value[1]] = counts.get(value[1], 0) + 1

应该是

counts[value[1]] = counts.get(value[1], 0) + 1
counts[value[1]] = counts.get(value[1], 0) + 1

should be

counts[value[1]] = counts.get(value[1], 0) + 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文