Swift - 按范围对数组元素排序
Swift - Sort array element by range
我目前正在使用 "Charts" pod。
我的应用显示运动员成绩的条形图,其中:
- X Axis: number of reps / time / rounds / weight
- Y Axis: number of athletes
我想收集不同组的代表人数。
类似于:10 < x < 20、20 < x < 30 等...
而不是真正的代表总数。
类似的东西:
最好的方法是什么?我考虑了一些方法:
例如,- 将重复次数取整 以将 19 和 15 转换为 10 和 10(对于 10 < x < 20 类别)
该方法的问题是我不知道我是否可以对“时间(秒)
做同样的事情
创建一个包含字典的新数组,类似于:
[[“10-20”:15、17、19],[“20-30”:21、22、22、24],等等]
但我不知道如何实现...
最好的方法是什么?
您可以使用 Dictionary
的 init(grouping:by:)
初始化器来创建这样一个字典:
let array = [15,17,19,22,24,24,27]
let dict = Dictionary(grouping: array, by: { [=10=] / 10 })
// dict is [2: [22, 24, 24, 27], 1: [15, 17, 19]]
如果我没理解错的话,你可能有一堆 Athlete
而他们有一个 reps
属性。您可以改为按 [=17=].reps / 10
分组:
Dictionary(grouping: athletes, by: { [=11=].reps / 10 })
然后将键和值映射到:
.map { ("\([=12=].key * 10) - \(([=12=].key + 1) * 10)", [=12=].value.count) }
// now you have this:
// [("20 - 30", 4), ("10 - 20", 3)]
我目前正在使用 "Charts" pod。
我的应用显示运动员成绩的条形图,其中:
- X Axis: number of reps / time / rounds / weight
- Y Axis: number of athletes
我想收集不同组的代表人数。
类似于:10 < x < 20、20 < x < 30 等... 而不是真正的代表总数。
类似的东西:
最好的方法是什么?我考虑了一些方法:
-
例如,
- 将重复次数取整 以将 19 和 15 转换为 10 和 10(对于 10 < x < 20 类别) 该方法的问题是我不知道我是否可以对“时间(秒) 做同样的事情
创建一个包含字典的新数组,类似于:
[[“10-20”:15、17、19],[“20-30”:21、22、22、24],等等]
但我不知道如何实现...
最好的方法是什么?
您可以使用 Dictionary
的 init(grouping:by:)
初始化器来创建这样一个字典:
let array = [15,17,19,22,24,24,27]
let dict = Dictionary(grouping: array, by: { [=10=] / 10 })
// dict is [2: [22, 24, 24, 27], 1: [15, 17, 19]]
如果我没理解错的话,你可能有一堆 Athlete
而他们有一个 reps
属性。您可以改为按 [=17=].reps / 10
分组:
Dictionary(grouping: athletes, by: { [=11=].reps / 10 })
然后将键和值映射到:
.map { ("\([=12=].key * 10) - \(([=12=].key + 1) * 10)", [=12=].value.count) }
// now you have this:
// [("20 - 30", 4), ("10 - 20", 3)]