问题
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