如何在多维数组中快速找到项的索引?
发布时间:2020-12-14 05:25:19 所属栏目:百科 来源:网络整理
导读:假设我有这个数组: let a = [[1,2,3],[4,5,6],[7,8,9]] 现在我想要这样的东西: public func indicesOf(x: Int,array: [[Int]]) - (Int,Int) { ... } 所以我可以这样称呼它: indicesOf(7,array: a) // returns (2,0) 当然,我可以使用: for i in 0..array.
假设我有这个数组:
let a = [[1,2,3],[4,5,6],[7,8,9]] 现在我想要这样的东西: public func indicesOf(x: Int,array: [[Int]]) -> (Int,Int) { ... } 所以我可以这样称呼它: indicesOf(7,array: a) // returns (2,0) 当然,我可以使用: for i in 0..<array.count { for j in 0..<array[i].count { if array[i][j] == x { return (i,j) } } } 但这甚至不是很接近! 我想要一种方法来做到这一点很快乐.我想也许我可以使用reduce或map?
您可以使用enumerate()和indexOf()稍微简化代码.
此函数还应返回一个可选元组,因为该元素 可能不存在于“矩阵”中.最后,你可以使它通用: func indicesOf<T: Equatable>(x: T,array: [[T]]) -> (Int,Int)? { for (i,row) in array.enumerate() { if let j = row.indexOf(x) { return (i,j) } } return nil } 您还可以将其作为嵌套的Equatable数组的扩展 extension Array where Element : CollectionType,Element.Generator.Element : Equatable,Element.Index == Int { func indicesOf(x: Element.Generator.Element) -> (Int,Int)? { for (i,row) in self.enumerate() { if let j = row.indexOf(x) { return (i,j) } } return nil } } if let (i,j) = a.indicesOf(7) { print(i,j) } 斯威夫特3: extension Array where Element : Collection,Element.Iterator.Element : Equatable,Element.Index == Int { func indices(of x: Element.Iterator.Element) -> (Int,row) in self.enumerated() { if let j = row.index(of: x) { return (i,j) } } return nil } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |