c# - Python 的 defaultdict 的模拟?

标签 c# .net

是否有 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/

相关文章:

c# - 如何使用epplus设置页脚中的页码从指定编号开始

c# - 在单独的类中引用表单

.net - 已安装 VSTO x64 运行时但找不到

C# 在 C++ 中对 (number & number) 的正确用法?

c# - 如何在Winform应用程序中限制父控件内的子控件?

c# - 如何创建确定性指南

.net - 将此 app.config xml 转换为代码吗? (世界CF)

c# - 是否可以在迭代 ICollection 时确定当前位置?

.net - 我可以在 Neo4j 中使用 .NET 中的空间数据吗?

.net - .NET 中的 HTTP 端口扫描