加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Python默认的类比?

发布时间:2020-12-15 08:28:14 所属栏目:百科 来源:网络整理
导读:是否有 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
是否有 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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读