gpt4 book ai didi

ruby - 根据每个嵌套数组的第一个元素对 Ruby 数组重新排序

转载 作者:数据小太阳 更新时间:2023-10-29 08:52:25 24 4
gpt4 key购买 nike

我的目标是将 a 转换为 b:

a = [["a","b"], ["d", "c"], ["a", "o"], ["d", "g"], ["c", "a"]]
b = [[["a","b"], ["a", "o"]], ["c", "a"], [["d", "c"], ["d", "g"]]

它们按每个嵌套数组中的第一个元素分组。到目前为止,我有:

def letter_frequency(c)
d = Hash.new(0)
c.each do |v|
d[v] += 1
end
d.each do |k, v|
end
end

def separate_arrays(arry)
arry2 = []
arry3 = []
big_arry = []
y = 0
while y < arry.length
arry2.push(arry[y][0])
arry3.push(arry[y][1])
y += 1
end
freq = letter_frequency(arry2)
front = arry.slice!(0..(freq["a"] - 1))
end

separate_arrays(a)

这不仅看起来有点矫枉过正,而且现在可以保证“a”将是合法的哈希键,所以最后一部分不起作用。感谢您的帮助。

最佳答案

你可以尝试做这样的事情:

a.group_by(&:first).values.map {|e| e.length > 1 ? e : e.flatten}
# => [[["a", "b"], ["a", "o"]], [["d", "c"], ["d", "g"]], ["c", "a"]]

我使用以下方法:

Enumerable#group_by (按数组的第一个元素,如您的问题):

Returns a hash, which keys are evaluated result from the block, and values are arrays of elements in enum corresponding to the key.

Hash#values :

Returns a new array populated with the values from hsh. See also Hash#keys.

Enumerable#map (必需,因为当只有一个匹配项时您不想获得嵌套数组,例如 c 字母):

Returns a new array with the results of running block once for every element in enum.

Enumerable#flatten :

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten

关于ruby - 根据每个嵌套数组的第一个元素对 Ruby 数组重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9564657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com