Arrays 非嵌套数组Swift的嵌套数组andices
这是我想自学的东西。我希望嵌套的Arrays 非嵌套数组Swift的嵌套数组andices,arrays,swift,Arrays,Swift,这是我想自学的东西。我希望嵌套的索引数组中有一对元素指向numberArray中的元素: IOW:如果indexArray具有[[0,2],[3,4]我希望嵌套元素指向numberArray中的元素\0和\2以及numberArray中的元素3和4 func findNumIndex(numberArray: [Int], indexArray: [[Int]]) -> Int { // Use the NESTED index elements to arrive
索引数组中有一对元素指向numberArray
中的元素:
IOW:如果indexArray
具有[[0,2],[3,4]
我希望嵌套元素指向numberArray
中的元素\0
和\2
以及numberArray
中的元素3和4
func findNumIndex(numberArray: [Int], indexArray: [[Int]]) -> Int {
// Use the NESTED index elements to arrive at element index in numberArrray
}
findNumIndex(nums: [0,1,2,3,4,5,6,7,8,9], queries: [[0,1],[1,2],[3,4]])
// We would look at index 0 and 1, index 1 and 2, index 3 and 4 and get the numbers/
起初我想把阵列展平,但那不是我想要的 这似乎可以通过一个简单的地图来实现:
indexArray.map { $0.map { numberArray[$0] } }
这似乎可以通过一个简单的地图来实现:
indexArray.map { $0.map { numberArray[$0] } }
有点过度设计,但这是一个非常方便的扩展,适用于很多情况:
extension RandomAccessCollection where Self.Index == Int {
subscript<S: Sequence>(indices indices: S) -> [Self.Element]
where S.Iterator.Element == Int {
return indices.map{ self[$0] }
}
}
let input = ["a", "b", "c", "d", "e"]
let queries = [[0, 1], [1, 2], [3, 4]]
let result = queries.map{ input[indices: $0] }
print(result) // => [["a", "b"], ["b", "c"], ["d", "e"]]
扩展RandomAccessCollection,其中Self.Index==Int{
下标(索引:S)->[Self.Element]
其中S.Iterator.Element==Int{
返回索引.map{self[$0]}
}
}
让输入=[“a”、“b”、“c”、“d”、“e”]
让查询=[[0,1],[1,2],[3,4]]
让result=querys.map{input[index:$0]}
打印(结果)/=>[[“a”、“b”]、[“b”、“c”]、[“d”、“e”]]
有点过度设计,但这是一个非常方便的扩展,适用于很多情况:
extension RandomAccessCollection where Self.Index == Int {
subscript<S: Sequence>(indices indices: S) -> [Self.Element]
where S.Iterator.Element == Int {
return indices.map{ self[$0] }
}
}
let input = ["a", "b", "c", "d", "e"]
let queries = [[0, 1], [1, 2], [3, 4]]
let result = queries.map{ input[indices: $0] }
print(result) // => [["a", "b"], ["b", "c"], ["d", "e"]]
扩展RandomAccessCollection,其中Self.Index==Int{
下标(索引:S)->[Self.Element]
其中S.Iterator.Element==Int{
返回索引.map{self[$0]}
}
}
让输入=[“a”、“b”、“c”、“d”、“e”]
让查询=[[0,1],[1,2],[3,4]]
让result=querys.map{input[index:$0]}
打印(结果)/=>[[“a”、“b”]、[“b”、“c”]、[“d”、“e”]]
这没什么错。我的建议是:仔细阅读map
、flatMap
、reduce
和filter
方法。它们在很多情况下都非常有用!这没什么错。我的建议是:仔细阅读map
、flatMap
、reduce
和filter
方法。它们在很多情况下都非常有用!太酷了!谢谢大家!我有一些好东西要嚼,太酷了!谢谢大家!我有一些好东西要嚼。