微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/csharp/243687.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐