【问题标题】:从多个数组(字符串数组的数组)中删除重复项的有效方法
【发布时间】:2022-01-22 21:44:51
【问题描述】:

我正在尝试找出一种有效的方法来从字符串数组中删除重复项,但不是在单个数组中,而是从所有数组中。

很难解释,所以我举个例子:

[
  ["Word1", "Word2", "Word3", "Word4"],
  ["Word1", "Word5", "Word3", "Word4"],
  ["Word1", "Word2", "Word3", "Word7"],
]

预期结果:

[
  ["Word2", "Word4"],
  ["Word5", "Word4"],
  ["Word2", "Word7"],
]

索引 0:已删除,因为所有索引 0 都是相同的。

索引 1:保留,因为并非所有索引 1 都是相同的。 等等……

我离得越近

def clean_duplicates(attributes)
    valid_attributes = attributes.map { [] }

    attributes.first.count.times.each do |i|
        next if attributes.all? { |v_attrs| v_attrs[i] == attributes.last[i] }

        attributes.each_with_index do |_, v|
            valid_attributes[v].push(attributes[v][i])
        end
    end

    valid_attributes
end

clean_attributes([["Word1", "Word2", "Word3", "Word4"], ["Word1", "Word5", "Word3", "Word4"], ["Word1", "Word2", "Word3", "Word7"]])

=> [["Word2", "Word4"], ["Word5", "Word4"], ["Word2", "Word7"]]

有没有更好的办法?

谢谢!

【问题讨论】:

    标签: arrays ruby-on-rails ruby


    【解决方案1】:

    这是一个使用 Array#transpose 和 Array#select 的解决方案

        [["Word1", "Word2", "Word3", "Word4"], ["Word1", "Word5", "Word3", "Word4"], ["Word1", "Word2", "Word3", "Word7"]]
    .transpose
    .select {|i| i.uniq.size > 1}
    .transpose
    

    第一步是转置输入得到以下内容:

    [["Word1", "Word1", "Word1"], ["Word2", "Word5", "Word2"], ["Word3", "Word3", "Word3"], ["Word4", "Word4", "Word7"]]
    

    那么你只想保留不完全相同的元素。

    select { |i| i.uniq.size > 1 } 
    

    将只选择那些值不相同的元素,给你:

    [["Word2", "Word5", "Word2"], ["Word4", "Word4", "Word7"]]
    

    最后你转置到你想要的结果。

    transpose
    [["Word2", "Word4"], ["Word5", "Word4"], ["Word2", "Word7"]]
    

    【讨论】:

    • 我以前从未见过转置!灵动优雅!谢谢!
    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 2018-04-02
    • 2017-12-30
    • 2015-11-11
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多