Swift:配对数组元素的最佳方式是什么? [英] Swift: What's the best way to pair up elements of an Array
问题描述
我遇到了一个需要成对迭代数组的问题。什么是最好的方法来做到这一点?或者,作为一种替代方法,将数组转换为数组对的最佳方法是什么?(然后可以正常迭代)?
这是我得到的最好的。它要求 output
是一个 var
,它并不真实。有没有更好的方法?
let input = [1,2,3,4,5,6]
var output = [(Int,Int)]()
for my stride(from:0,to:input.count - 1,by:2){
output.append((input [i],input [i + 1]))
}
print(output)// [(1,2),(3 ,(4,5,6)]
// let desiredOutput = [(1,2),(3,4),(5,6)]
// print您可以将 map >而不是迭代它,
允许将结果作为常量: let input = [1,2,3,4,5,6]
让output = stride(from:0,to:input.count - 1,by:2).map {
(输入[$ 0],输入[$ 0 + 1])$ b $ b}
print(输出)// [(1,2),(3,4), (5,6)]
如果您只需要遍历这些对并且给定的数组很大
,那么避免使用懒惰创建中间
数组可能是有利的映射:
for(left,right)in stride(from:0,to:input.count - 1,by:2 )
.lazy
.map({(input [$ 0],input [$ 0 + 1])}){
print(left,right)
}
I came across a problem that required iterating over an array in pairs. What's the best way to do this? Or, as an alternative, what's the best way of transforming an Array into an Array of pairs (which could then be iterated normally)?
Here's the best I got. It requires output
to be a var
, and it's not really pretty. Is there a better way?
let input = [1, 2, 3, 4, 5, 6]
var output = [(Int, Int)]()
for i in stride(from: 0, to: input.count - 1, by: 2) {
output.append((input[i], input[i+1]))
}
print(output) // [(1, 2), (3, 4), (5, 6)]
// let desiredOutput = [(1, 2), (3, 4), (5, 6)]
// print(desiredOutput)
解决方案 You can map the stride instead of iterating it, that
allows to get the result as a constant:
let input = [1, 2, 3, 4, 5, 6]
let output = stride(from: 0, to: input.count - 1, by: 2).map {
(input[$0], input[$0+1])
}
print(output) // [(1, 2), (3, 4), (5, 6)]
If you only need to iterate over the pairs and the given array is large
then it may be advantageous to avoid the creation of an intermediate
array with a lazy mapping:
for (left, right) in stride(from: 0, to: input.count - 1, by: 2)
.lazy
.map( { (input[$0], input[$0+1]) } ) {
print(left, right)
}
这篇关于Swift:配对数组元素的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!