我很少接触Ruby,所以我在格式化数据方面遇到了困难。
我有一个哈希表,其中包含一些具有相同值的键,例如:
{"key" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value1", "key5" => "value2" ..}
我正在尝试将其转换为一个包含按值分组的键的数组。
[["key","key4"],["key2","key5"],["key3"]]
new_hash = {}
hash.each do |key, value|
new_hash[value] ||= []
new_hash[value] << key
end
array = new_hash.values # => [["key", "key4"], ["key2", "key5"], ["key3"]]
hash = {
"key" => "value1",
"key2" => "value2",
"key3" => "value3",
"key4" => "value1",
"key5" => "value2"
}
hash.group_by { |key, value| value }.values.map { |pairs| pairs.map &:first }
# => [["key", "key4"], ["key2", "key5"], ["key3"]]
hash.group_by{|k,v| v}.map{|k,v| v.reduce([]){|res,n| res << n.first}}
v.map(&:first)
。 - Niklas B.
h.group_by(&:last).map { |_,y| y.map(&:first) }
。 - Niklas B.group_by
,所以甚至没有想到它。 - Andrew Marshalllambda { |x,x| 3 }
失败,而lambda { |_,_| 3 }
成功的原因。 - Niklas B.