[[1, [-1, 1]], [1, [20, 8]], [1, [30, 4]], [1, [40, 2]], [1, [41, 6]], [1, [70, 243]]]
转换为此样式[1,[[-1,1],[20,8],[30,4]...]
或哈希[1 => ...]
我怎么能这样做?谢谢!
答案 0 :(得分:6)
Dict方法:
array = [your array]
dict = {}
array.each{ |a| (dict[a[0]] ||= []) << a[1] }
为了清楚起见,查克的建议将带来:
array = [your array]
dict = Hash.new {|h,k| h[k] = []}
array.each{ |a| dict[a[0]] << a[1] }
然后,您可以按照您想要的样式从中获取数组:
new_arr = dict.select{|k,v| [k, v]}
哪个会给你:
[[1, [[-1, 1], [20, 8], [30, 4], [40, 2], [41, 6], [70, 243]]]]
注意额外的数组,因为如果你有2开头的数组,你最后会有另一个数组。因此new_arr[0]
会为您提供您最初寻找的数组。
答案 1 :(得分:2)
如果您希望它为Hash
,则只需
h = Hash[ary.group_by(&:first).map {|k, v| [k, v.map(&:last)] }]
如果您想将其作为Array
,则只需将Hash
转换为Array
:
a = *h
答案 2 :(得分:0)
你可以这样做:
array = [[1, [-1, 1]], [1, [20, 8]], [1, [30, 4]],
[1, [40, 2]], [1, [41, 6]], [1, [70, 243]]]
# map into hashes that can be merged together
hashes = array.map do |key,value|
{ key => [value] }
end
# fold all hashes into one hash by merging the values by key
merged_hash = hashes.inject({}) do |accu,value|
accu.merge!(value) {|_,o,n| o|n }
end
这可以写成一个不那么容易的单行词:
array.map{|k,v|{k=>[v]}}.inject({}){|a,v|a.merge!(v){|_,o,n|o|n}}
#==> {1=>[[-1, 1], [20, 8], [30, 4], [40, 2], [41, 6], [70, 243]]}