c# – Python默认的类比?

前端之家收集整理的这篇文章主要介绍了c# – Python默认的类比?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有 Pythondefaultdict的.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());
原文链接:https://www.f2er.com/csharp/243687.html

猜你在找的C#相关文章