问题描述
我有一个数组,如 [0.75,0.0050000000000000001,0.0050000000000000001,0.0050000000000000001,0.0050000000000000001,0.0050000000000000001,0.0040000000000000001,...]
,我需要删除重复。我只想集中在小数点后的前3位数字。如何做到这一点?
I have an array of values like [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0040000000000000001, ...]
and I need to remove the duplicates. I only want to focus on the first 3 digits after the decimal point. How do I do this?
推荐答案
您可以使用NumberFormatter修改最小和最大分数数字,并使用set过滤重复元素:
You can use NumberFormatter to fix the minimum and maximum fraction digits and use a set to filter the duplicate elements:
let array = [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0040000000000000001]
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.minimumFractionDigits = 3
numberFormatter.maximumFractionDigits = 3
var set = Set<String>()
let orderedSet: [Double] = array.flatMap {
guard let string = numberFormatter.string(for: $0) else { return nil }
return set.insert(string).inserted ? $0 : nil
}
orderedSet // [0.75, 0.005, 0.004]
如果您需要Strings(由@Hamish建议):
If you need Strings (as suggested by @Hamish):
var set = Set<String>()
let orderedSet: [String] = array.flatMap {
guard let string = numberFormatter.string(for: $0) else { return nil }
return set.insert(string).inserted ? string : nil
}
orderedSet // ["0.750", "0.005", "0.004"]
这篇关于Swift:如何从双数组中删除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!