有没有一种简单的方法来计算两个数组之间的差异 [英] Is there an easy way to compute difference between two arrays

查看:63
本文介绍了有没有一种简单的方法来计算两个数组之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算Swift中两个数组中的值之间的差。我想减去两个数组之间每个索引的值。

I am trying to compute the difference between the values in two arrays in Swift. I want to subtract values at each index between two arrays.

我尝试执行以下操作:

var array1 : [Double] = [1, 2, 3, 4, 5]
var array2 : [Double] = [2, 3, 4, 5, 6]

var result = array2 - array1

预期答案:


结果= [1、1、1、1、1]

result = [1, 1, 1, 1, 1]

我收到以下错误消息:


二进制运算符'-'不能应用于两个'[Double]'操作数

Binary operator '-' cannot be applied to two '[Double]' operands

以下工作:

var array1 : [Double] = [1, 2, 3, 4, 5]
var array2 : [Double] = [2, 3, 4, 5, 6]

let velocity = (0..<5).map { array2[$0] - array1[$0] }
print(velocity)

我想了解是否有一种有效的方法来完成此任务。

I wanted to understand if there is an efficient way to accomplish this.

推荐答案

您的尝试效果很好。通常,您需要检查哪个数组的元素较少(以防万一):

Your attempt works quite well. In general, you would need to check which array has the fewer elements (just in case):

(0..<(min(array1.count, array2.count))).map { array2[$0] - array1[$0] }

或者,正如康纳在回答中提到的那样,使用 zip ,它可以为您处理数组长度的比较。

Or, as Connor mentioned in their answer, use zip, which handles this comparison of array lengths for you.

zip(lhs, rhs).map { $0.0 - $0.1 }

您可以再进一步一步,并重载-运算符以实现所需的语法( array1-array2 ):

You can go one step further and overload the - operator to achieve the syntax you wanted (array1 - array2):

func -<T: Numeric>(lhs: [T], rhs: [T]) -> [T] {
    return zip(lhs, rhs).map(-)
}

// usage:
print([1,2,3] - [0, 1, 2])

但请注意,对其他人来说,可能是尚不清楚一个数组减去另一个数组的含义。

But do note that, to other people, it might be quite unclear what an array "minus" another array means.

这篇关于有没有一种简单的方法来计算两个数组之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆