简体   繁体   English

python 中 unorderd_map 的替代方案是什么? 我们知道key中的默认值:c++中的值为零

[英]What is the alternative of unorderd_map in python? We know that default value in key: value is zero in c++

//in C++
unordered_map<int,int>m;
for (i = 0; i < n; ++i) {
          m[arr[i]]++;
}

#in python
my_dict = {}
for i in range(len(arr)):
       my_dict[arr[i]] += 1 #This gives key error

I am sure that the default value is set to zero in C++, so it works.我确信 C++ 中的默认值设置为零,所以它可以工作。 How to go about it in Python?如何在 Python 中了解 go?

In python you could use defaultdict .在 python 你可以使用defaultdict

from collections import defaultdict

arr = [1,2,3]

my_dict = defaultdict(int)
for i in range(len(arr)):
    my_dict[arr[i]]+=1

As @Loocid suggested defaultdict is the way to go.正如@Loocid 建议的那样, defaultdict是通往 go 的方式。 The other option is to use get() with a default value:另一种选择是使用带有默认值的get()

my_dict = {}
for i in range(len(arr)):
    my_dict[arr[i]] = my_dict.get(arr[i], 0) + 1

or avoid the indexing with或避免使用索引

my_dict = {}
for a in arr:
    my_dict[a] = my_dict.get(a, 0) + 1

Written with a smartphone and unchecked用智能手机写的,未经检查

The alternative is defaultdict .另一种方法是defaultdict You can use a function to set a default value.您可以使用 function 设置默认值。

Example:例子:

from collections import defaultdict

def not_inside_dict():
    return 0;

d = defaultdict(not_inside_dict)

d[1] = 7
d[2] = 9

for i in range(1,4):
    print(d[i])

Result:结果:

7
9
0

You can also declare like this:你也可以这样声明:

from collections import defaultdict

d = defaultdict(int)

d[1] = 7
d[2] = 9

for i in range(1,4):
    print(d[i])

And it will still return 0 when encountering elements not inside the dict.当遇到不在字典内的元素时,它仍然会返回0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM