c# – Python默认的类比?

c# – Python默认的类比?,第1张

概述是否有 Python的 defaultdict的.NET模拟?我发现编写短代码很有用,例如.计数频率: >>> words = "to be or not to be".split()>>> print words['to', 'be', 'or', 'not', 'to', 'be']>>> from collections import defaultdict>>> frequenci 是否有 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 frequencIEsdefaultdict(<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());
总结

以上是内存溢出为你收集整理的c# – Python默认类比?全部内容,希望文章能够帮你解决c# – Python默认的类比?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1249505.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存