Có tương tự .NET của defaultdict
của Python không? Tôi thấy hữu ích khi viết mã ngắn, ví dụ: tần số đếm:Tương tự với defaultdict của Python?
>>> 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})
Vì vậy, lý tưởng trong C# Tôi có thể viết:
var frequencies = new DefaultDictionary<string,int>(() => 0);
foreach(string word in words)
{
frequencies[word] += 1
}
nào 'defaultdict' làm gì ? Tôi không quen với python. Chỉnh sửa: Nó chỉ là một từ điển có giá trị mặc định cho các phím. Bạn có thể phân lớp 'Dictionary' và thực hiện chức năng. – Romoku
Câu trả lời của Jon Skeet có thể giúp: http://stackoverflow.com/a/2601501/1786606. – Vladimir