是否有
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 }
解决方法
我不认为有一个等价物,但鉴于你的例子,你可以用LINQ做到这一点:
var words = new List<string>{ "One","Two","Three","One" }; var frequencies = words.GroupBy (w => w).ToDictionary (w => w.Key,w => w.Count());