正在尝试翻译 some methods用 Python 写成 C#。该行看起来像这样:
d[p] = d.setdefault(p, 0) + 1
setdefault 到底做了什么?我可以在 C# 字典中使用类似的东西吗?或者更确切地说,我如何将该行翻译成 C#?
最佳答案
来自Python docs :
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
在.NET框架中没有直接实现,但是你可以定义一个扩展方法:
public static V SetDefault<K,V>(this IDictionary<K,V> dict, K key, V @default)
{
V value;
if (!dict.TryGetValue(key, out value))
{
dict.Add(key, @default);
return @default;
}
else
{
return value;
}
}
用法:
string key;
Dictionary<string, int> dict;
dict[key] = dict.SetDefault(key, 0) + 1;
关于C#:C# 中的字典是否具有类似于 Python setdefault 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1514457/