python - C++中是否有任何等效于python中字典的get函数的函数?

标签 python c++

我正在尝试解决this问题陈述。
它基本上希望您将给定 vector 中的重复项更改为唯一形式:
例如:["name","name","name1"]-> ["name","name2","name1"] ...
所以我想到了使用std::map创建一个dictionary(我也可以在这里使用unordered_map)

这就是我使用 map 的方式:

std::vector<std::string> getFolderNames(std::vector<std::string>& names) {
    std::vector<std::string> vec_list_of_folders;
    std::map<std::string, int> map_of_names;
    for (const auto& name : names) {
        if (map_of_names.find(std::string(name)) == map_of_names.end()) {
            map_of_names.insert(std::make_pair(name, 1));
        }
        else {
            map_of_names[name] += 1;
        }
    }
    puts("");
    return vec_list_of_folders;
}
该函数仍处于 Debug模式(这说明了为什么其中一半内容未编码的原因)
我认为重要的部分是:
for (const auto& name : names) {
    if (map_of_names.find(std::string(name)) == map_of_names.end()) {
        map_of_names.insert(std::make_pair(name, 1));
    }
    else {
        map_of_names[name] += 1;
    }
}

我想知道是否有简单的方法可以做到这一点。类似于python中的以下代码:
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = dict()
for file_name in file_names:
    example_dict[file_name] = example_dict.get(file_name, 0) + 1  # this is the function I'm searching an equivalent for
print(example_dict)
我该怎么办?

最佳答案

您的重要零件代码等效于:

for (const auto& name : names) {
    map_of_names[name] += 1;
}
如果未找到name,则值类型为default-constructed,而default-constructed int为0。
您可以使用defaultdict在Python中执行类似的操作:
import collections
file_names = ["file1", "file2", "file3", "file1"]
print(*file_names)
example_dict = collections.defaultdict(int)
for file_name in file_names:
    example_dict[file_name] += 1
print(example_dict)

关于python - C++中是否有任何等效于python中字典的get函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608228/

相关文章:

python - 如何通过颜色图为轮廓标签着色?

c++ - 扩展 std::priority_queue 功能

c++ - 预测 std::unordered_set 或 std::unordered_map 的调整大小/重新散列

c++ - 视觉 C++ 开发

python - 如何使用 python 脚本更改 tcp keepalive 计时器?

python - 用另一个文件中的单词替换替换单词

python - 将多个字符串作为一行写入文本文件

python - pyspark sql : Create a new column based on whether a value exists in a different DataFrame's column

c++ - 递归部分解释

c++ - 嵌入式系统单元测试