如果我得到这个数组:
[0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到:
[2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
这个答案将保留副本的值,但我也想删除该值.
请注意,您需要导入Foundation才能使用NSCountedSet.如果你需要一个纯粹的迅速解决,以找到一个集合的独特元素,你可以扩展它制约因素的Equatable协议和检查,如果你能不能找到再次检查,如果指数(作者:元)元素索引==零使用index(after :)元素索引作为集合子序列的startIndex:
编辑/更新:Swift 4.2.1
需要注意的是延长RangeReplacebleCollection它将覆盖StringProtocol类型String和Substring以及:
约束元素 Equatable
extension RangeReplaceableCollection where Element: Equatable {
var uniqueElements: Self {
filter {
guard let index = firstIndex(of: $0) else { return false }
return self[self.index(after: index)...].firstIndex(of: $0) == nil
}
}
mutating func removeAllNonUniqueElements() { self = uniqueElements }
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要保留集合原始顺序,则可以利用新的Dictionary初始化程序,但这需要将元素约束为Hashable:
init<S>(grouping values: S, by keyForValue: (S.Element) throws -> Dictionary<Key, Value>.Key) rethrows where Value == [S.Element], S : Sequence
Run Code Online (Sandbox Code Playgroud)
并保持值等于1的键
extension RangeReplaceableCollection where Element: Hashable {
var uniqueElementsSet: Set<Element> {
Set(Dictionary(grouping: self, by: { $0 }).compactMap{ $1.count == 1 ? $0 : nil })
}
}
Run Code Online (Sandbox Code Playgroud)
游乐场测试
let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
numbers.uniqueElements // [4, 2, 3]
Run Code Online (Sandbox Code Playgroud)
如果您需要保留集合的顺序,您可以获得此答案中显示的元素频率并过滤唯一元素:
extension Sequence where Element: Hashable {
var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
}
Run Code Online (Sandbox Code Playgroud)
extension RangeReplaceableCollection where Element: Hashable {
var uniqueElements: Self { filter { frequency[$0] == 1 } }
mutating func removeAllNonUniqueElements() { self = uniqueElements }
}
Run Code Online (Sandbox Code Playgroud)
游乐场测试
let numbers = [0, 0, 1, 1, 1, 2, 3, 4, 5, 5]
numbers.uniqueElements // [2, 3, 4]
var string = "0011123455"
string.uniqueElements // "234"
string.uniqueElementsSet // {"4", "3", "2"}
print(string) // "0011123455\n"
// mutating the string
string.removeAllNonUniqueElements()
print(string) // 234
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1369 次 |
| 最近记录: |