gpt4 book ai didi

arrays - 根据下一个对象过滤数组

转载 作者:可可西里 更新时间:2023-11-01 02:17:01 24 4
gpt4 key购买 nike

我正在编写一些代码来从运动传感器中过滤掉驾驶行程。我发现最好的方法是根据以下内容将子数组添加到嵌套数组:

  • 检测首次发生的有把握的汽车事件
  • 将以下所有运动事件添加到同一事件数组中,直到第一个有把握的观察结果表明情况并非如此。

例如

automotive confidence 2 //Add
automotive confidence 2 //Add
automotive confidence 2 //Add
walking confidence 2 //Add the sub-array to the master array and start over on the next confident automotive event.

目前我是这样做的:

        //Remove all uncertain values.
let confidentActivities = activities!.filter{$0.confidence.rawValue == 2}

var needsNew = true
var automotiveActivities:Array<Array<CMMotionActivity>> = Array() //Master array to contain subarrays of automotiveactivity arrays
var automotiveActivitySession:Array<CMMotionActivity> = Array()
for activity in confidentActivities {
if activity.automotive && (!activity.cycling && !activity.running && !activity.walking){
if needsNew {
needsNew = false
}
automotiveActivitySession.append(activity)
} else {
if !needsNew {
//If user is no longer in car, store a cpoy of the session and reset the array
automotiveActivities.append(Array(automotiveActivitySession))
automotiveActivitySession = []
needsNew = true
}
}
}

这个解决方案不是很优雅。有没有什么方法可以使用 Swift 的 Array.filter{} 来使这种排序更漂亮?

最佳答案

过滤器不会这样做,但您可以使用 reduce

下面的示例展示了如何将连续 “A”(表示汽车事件)的运行收集到数组数组中的数组中:

let data = ["A","A","A","B","A","A","B","A","A","A","A","B","B","B","A","B","A","A","A","A","A","A","B","A"]
var res = [[String]]()
_ = data.reduce("") { (last: String, current: String) in
if current == "A" {
if last != "A" {
res.append([String]())
}
res[res.count-1].append(current)
}
return current
}
print(res)

先验值作为第一个参数传递给reduce 函数。这使得该函数可以决定是追加到当前列表还是开始一个新列表。

本次运行结果如下:

[   ["A", "A", "A"]
, ["A", "A"]
, ["A", "A", "A", "A"]
, ["A"]
, ["A", "A", "A", "A", "A", "A"]
, ["A"]]

关于arrays - 根据下一个对象过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970997/

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