是否有 Python 的 defaultdict
的 .NET 类似物? ?我发现编写简短的代码很有用,例如。计数频率:
>>> words = "to be or not to be".split()
>>> print words
['to', 'be', 'or', 'not', 'to', 'be']
>>> from collections import defaultdict
>>> frequencies = defaultdict(int)
>>> for word in words:
... frequencies[word] += 1
...
>>> print frequencies
defaultdict(<type 'int'>, {'not': 1, 'to': 2, 'or': 1, 'be': 2})
理想情况下,我可以在 C# 中编写:
var frequencies = new DefaultDictionary<string,int>(() => 0);
foreach(string word in words)
{
frequencies[word] += 1
}
最佳答案
这是一个简单的实现:
public class DefaultDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : new()
{
public new TValue this[TKey key]
{
get
{
TValue val;
if (!TryGetValue(key, out val))
{
val = new TValue();
Add(key, val);
}
return val;
}
set { base[key] = value; }
}
}
以及您将如何使用它:
var dict = new DefaultDictionary<string, int>();
Debug.WriteLine(dict["foo"]); // prints "0"
dict["bar"] = 5;
Debug.WriteLine(dict["bar"]); // prints "5"
或者像这样:
var dict = new DefaultDictionary<string, List<int>>();
dict["foo"].Add(1);
dict["foo"].Add(2);
dict["foo"].Add(3);
关于c# - Python 的 defaultdict 的模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622622/