例如说我有一个像这样的数组:
var someArray = ["1", "1", "2"]
我需要把它放到两个看起来像这样的数组中:
["1","1"]
["2"]
我该如何解决这个问题?
任何帮助都会很棒!
答案 0 :(得分:6)
使用字典初始值设定项 init(grouping:by:) 然后通过访问 values 属性来获取数组。
示例:
let dic = Dictionary(grouping: someArray) { $0 }
let values = Array(dic.values)
print(values)
结果:
[["2"], ["1", "1"]]
答案 1 :(得分:4)
以下是一些事实(upvote和答案应该转到@kirander)
使用@kirander方法正在使用Dictionary
来映射O(N) runtime
和O(N) memory
中的对象。
其他解决方案主要在O(N*N) runtime
和O(N) memory
中运行。因此,对 1000 项目的随机数组进行分组将采用: 0.07s 与@kirander解决方案和 34s 。与其他解决方案。
func benchmark(_ title:String, code: ()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
code()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for \(title): \(timeElapsed) s.")
}
var array:[String] = []
for _ in 0...1000 {
array.append("\(Int(arc4random_uniform(10)))")
}
// @kirander solution 0.07s
benchmark("Dictionary", code: {
let dic = Dictionary(grouping: array, by: { $0 })
let values = Array(dic.values)
})
// @Bruno solution ~34s
benchmark("Array", code: {
var resultingArrays = [[String]]()
for value in array {
let ar = array.filter({ $0 == value })
if !resultingArrays.contains(where: {$0 == ar}) {
resultingArrays.append(ar)
}
}
})
答案 2 :(得分:1)
您可以尝试这样的事情:
var someArray = ["1", "1", "2"]
var resultingArrays = [[String]]()
for value in someArray {
let array = someArray.filter({ $0 == value })
if !resultingArrays.contains(where: {$0 == array}) {
resultingArrays.append(array)
}
}
答案 3 :(得分:-3)
你可以尝试这个:
let arrM = ["1","3","4","6","1","1","3"]
let arrSrtd = Array(Set(arrM))
for ele in arrSrtd{
let a = arrM.filter( {$0 == ele})
print(a)
}