C# element-wise difference between two lists of numbers

无人久伴 提交于 2021-02-04 21:20:27

问题


Assume

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;
}

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.

for instance, in python, this would be either

[ai-bi for ai,bi in zip(a,b)]

or even

np.array(a) - np.array(b)

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.


回答1:


Linq has a Zip method as well:

var diff = a.Zip(b, (ai, bi) => ai - bi);

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.



来源:https://stackoverflow.com/questions/58344429/c-sharp-element-wise-difference-between-two-lists-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!