假设我们有一个排序数组,如:
let sortedArray = [(A, 0), (B, 1), (C, 1), (D, 2), (E, 2), (F, 2)]
如何在元组中使用相同的第二个参数对它们进行分组,如:
let result = [
([A], 0),
([B, C], 1),
([D, E, F], 2)
]
[B, C]
和[D, E, F]
从排序数组继承相同的顺序。
编辑:
我的操场上有这些代码试图运行
let origin: [(String, Int)] = [("0", 0), ("1", 1), ("2", 1), ("2", 2), ("3", 2)]
if let last = origin.last {
let array = Array<([String], Int)>.init(repeating: ([], 0), count: last.1)
for (index, ele) in origin.enumerated() {
var b = array[index] as? ([String], Int)
b?.0.append(ele.0)
}
}
答案 0 :(得分:2)
您可以将reduce(into:)
与index(where:)
方法结合使用。如果您发现整数的索引会向数组附加一个新字符串,否则会附加一个带有单个字符串数组的新元组元素和相应的整数:
let sortedArray:[(string: String, integer: Int)] = [("A", 0), ("B", 1), ("C", 1), ("D", 2), ("E", 2), ("F", 2)]
let grouped = sortedArray.reduce(into: [(strings:[String], integer: Int)]()) { partial, tuple in
if let index = partial.index(where: {$0.integer == tuple.integer }) {
partial[index].strings.append(tuple.string)
} else {
partial.append(([tuple.string], tuple.integer))
}
}
print(grouped)
这将打印:
[(strings:[&#34; A&#34;],integer:0),(strings:[&#34; B&#34;,&#34; C&#34;],整数:1) ,(字符串:[&#34; D&#34;,&#34; E&#34;,&#34; F&#34;],整数:2)]
如果您不想为元组元素命名:
let sortedArray = [("A", 0), ("B", 1), ("C", 1), ("D", 2), ("E", 2), ("F", 2)]
let grouped = sortedArray.reduce(into: [([String],Int)]()) { partial, tuple in
if let index = partial.index(where: {$0.1 == tuple.1 }) {
partial[index].0.append(tuple.0)
} else {
partial.append(([tuple.0], tuple.1))
}
}