两个数字列表之间的C#元素明智差异 [英] C# element-wise difference between two lists of numbers
问题描述
假设
List<int> diff(List<int> a, List<int> b)
{
// assume same length lists
List<int> diff= new List<int>(a.Count);
for (int i=0; i<diff.Count; ++i)
{
diff[i] = a[i] - b[i];
}
return diff;
}
我希望某种形式的单行代码执行相同的操作,或者使用lambda进行某种操作,而不是重写所有样板代码.
I would like to have some kind of one-liner do the same, or something that uses a lambda, rather than re-writing all the boilerplate.
例如,在python中,可以是
for instance, in python, this would be either
[ai-bi for ai,bi in zip(a,b)]
甚至
np.array(a) - np.array(b)
有没有很好的方法用C#编写此代码?我所有的搜索都找到了删除或添加列表元素的方法,但是没有关于元素操作的方法.
Is there a nice way to write this in C#? All my searches find ways to remove or add list elements, but nothing about element-wise actions.
推荐答案
Linq has a Zip
method as well:
var diff = a.Zip(b, (ai, bi) => ai - bi);
请注意,您代码中的一个潜在错误是,如果 b
的元素少于 a
的元素,那么当您尝试访问范围之外的元素时会出现异常的 b
.只要两个收藏夹中都有商品, Zip
将只返回商品,这实际上是两个收藏夹长度中较短的一个.
Note that one potential bug in your code is if b
has fewer elements than a
then you'd get an exception when you try to access an element outside the range of b
. Zip
will only return items as long as both collections have items, which is effectively the shorter of the two collection lengths.
这篇关于两个数字列表之间的C#元素明智差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!