【问题标题】:Compare and Extract elements of 2 Arrays比较和提取 2 个数组的元素
【发布时间】:2019-05-26 11:14:49
【问题描述】:

我有 2 个String 数组:

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

我需要检查a 数组的哪些元素不在b 数组中,并将结果存储在一个名为c 的数组中。

我尝试使用这个扩展来实现这一点:

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    }
}

但它给我的结果是两个数组之间的差异(即“may”、“jun”),而我只需要a 数组中不在b 数组中的元素。我怎样才能做到这一点?

【问题讨论】:

  • 你不需要把两个东西都做成集合,只需要其中一个。一个操作数只需要迭代(Sequence 就足够了),一个操作数需要有快速的contains 性能(Set 是必要的)。

标签: arrays swift string


【解决方案1】:

你想从a中减去 b

return Array(thisSet.subtracting(otherSet))

或者

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        var temp = self
        temp.removeAll{ other.contains($0) }
        return temp
    }
}

【讨论】:

  • 这会反过来
  • ...a 数组的哪些元素不在bjun
  • 它给may,而它应该给jun
  • 这取决于用法:a.difference(from: b) 返回jun ?
  • @Sh_Khan 你确定吗?替代方案还删除了重复项,速度是Set 解决方案的两倍(经过 100000 次迭代测试)。
【解决方案2】:

你需要从 a 中减去 b

return Array(otherSet.subtracting(thisSet))

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

print(b.difference(from: a)) // jun

【讨论】:

  • 严格来说,您是从b 中减去a ?
  • 而结果中减去b的时候应该是jun
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多