【问题标题】:Transforming hash values based on condition after using group_by使用 group_by 后根据条件转换哈希值
【发布时间】:2022-01-18 12:06:54
【问题描述】:

我有一个 pipes 数组,它们具有以下属性:pipe_id gradegrade_confidence

我希望在数组中找到与具有相同 ID 的其他对象具有相同属性的对象。我一直在使用 group_by 和 transform_values 来查找只有一个等级的 ID - 效果很好(感谢Using group_by for only certain attributes 中的答案)。但是,如果可能的话,我仍然希望对最终结果保持grade_confidence。

class Pipes
  attr_accessor :pipe_id, :grade, :grade_confidence
  def initialize(pipe_id, grade, grade_confidence)
    @pipe_id = pipe_id
    @grade = grade
    @grade_confidence = grade_confidence
  end
end

pipe1 = Pipes.new("10001", "60", "A")
pipe2 = Pipes.new("10001", "60", "A")
pipe3 = Pipes.new("10001", "3", "F")
pipe4 = Pipes.new("1005", "15", "A")
pipe5 = Pipes.new("1004", "40", "A")
pipe6 = Pipes.new("1004", "40", "B")

pipes = []
pipes.push(pipe1, pipe2, pipe3, pipe4, pipe5, pipe6)

# We now have our array of pipe objects.

non_dups = pipes.group_by(&:pipe_id).transform_values { |a| a.map(&:grade).uniq }.select { |k,v| v.size == 1 }

puts non_dups

# => {"1005"=>["15"], "1004"=>["40"]}

希望

上面做了我想要的——因为“10001”有两个不同的grades,它被忽略了,“1004”和“1005”每个ID都有相同的等级。但我想保留grade_confidence,或者根据条件也包括grade_confidence

例如如果grade_confidence== "B" 最终结果将是# => {"1004"=>["40", "B"]}

如果grade_confidence== "A",最终结果将是# => {"1005"=>["15", "A"], "1004"=>["40", "A"]}

是否可以调整 transform_values 以允许这样做,还是我需要走另一条路?

谢谢

【问题讨论】:

    标签: ruby group-by hash hashmap


    【解决方案1】:

    你需要更新它:

    non_dups = pipes
      .group_by(&:pipe_id)
      .transform_values { |a| [a.map(&:grade).uniq, a.map(&:grade_confidence)]}
      .select { |_, (grades, _confidences)| grades.size == 1 }
      .transform_values {|grades, confindeces| [grades.first, confindeces.sort.first]}
    

    【讨论】:

    • 非常感谢,我现在也知道哪里出错了。
    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多