gpt4 book ai didi

c# - 像 Python 的 collections.Counter 库这样的 C# 库 -> 在 C# 中获取两个字典对象之间的值差异

转载 作者:太空狗 更新时间:2023-10-29 21:03:33 24 4
gpt4 key购买 nike

这就是我在 C# 中创建字典的方式。

   Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cheese", 2},
{"cakes", 1},
{"milk", 0},
{"humans", -1} // This one's for laughs
};

在 Python 中,如果你有这样的字典:

from collections import Counter

my_first_dict = {
"cheese": 1,
"cakes": 2,
"milk": 3,
}

my_second_dict = {
"cheese": 0,
"cakes": 1,
"milk": 4,
}

print Counter(my_first_dict) - Counter(my_second_dict)

>>> Counter({'cheese': 1, 'cakes': 1})

如您所见,Counter 在比较字典对象时非常有用。

C# 中是否有一个库可以让我做类似的事情,还是我必须从头开始编写代码?

最佳答案

只需几行代码,您就可以将两个字典连接在一起,然后根据给定的操作创建一个新字典:

Dictionary<string, int> d1 = new Dictionary<string, int>();
Dictionary<string, int> d2 = new Dictionary<string, int>();

var difference = d1.Join(d2, pair => pair.Key, pair => pair.Key, (a, b) => new
{
Key = a.Key,
Value = a.Value - b.Value,
})
.Where(pair => pair.Value > 0)
.ToDictionary(pair => pair.Key, pair => pair.Value);

您没有显示任何系统类来包装字典并为它们提供 - 运算符,但是如果您想要足够简单,您可以创建自己的系统类:

public class Counter<T> : IEnumerable<KeyValuePair<T, int>>
{
private IEnumerable<KeyValuePair<T, int>> sequence;
public Counter(IEnumerable<KeyValuePair<T, int>> sequence)
{
this.sequence = sequence;
}

public static Counter<T> operator -(Counter<T> first, Counter<T> second)
{
return new Counter<T>(first.Join(second
, pair => pair.Key, pair => pair.Key, (a, b) =>
new KeyValuePair<T, int>(a.Key, a.Value - b.Value))
.Where(pair => pair.Value > 0));
}

public IEnumerator<KeyValuePair<T, int>> GetEnumerator()
{
return sequence.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

关于c# - 像 Python 的 collections.Counter 库这样的 C# 库 -> 在 C# 中获取两个字典对象之间的值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com