gpt4 book ai didi

arrays - 将散列转换为散列数组

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

我有哈希,它的所有值都是数组,像这样:

list = { letter:  ['a', 'b', 'c'],
number: ['one', 'two', 'three'],
fruit: ['apple', 'pear', 'kiwi'],
car: ['vw', 'mb', 'bmw'],
state: ['la', 'ny', 'fl'],
color: ['red', 'white', 'black'],
tree: ['oak', 'pine', 'maple'],
animal: ['cat', 'dog', 'rat'],
clothes: ['tie', 'sock', 'glove'] }

事实上,这个散列可以有更多的键,值可以更大,但每个值的大小总是相同的(在本例中为三个)。

我想将这个散列转换为散列数组。

每个散列将具有原始散列的所有键和各自的值。

所以最后我想要:

list = [
{ letter: 'a', number: 'one', fruit: 'apple', car: 'vw', state: 'la',
color: 'red', tree: 'oak', animal: 'cat', clothes: 'tie' },

{ letter: 'b', number: 'two', fruit: 'pear', car: 'mb', state: 'ny',
color: 'white', tree: 'pine', animal: 'dog', clothes: 'sock' },

{ letter: 'c', number: 'three', fruit: 'kiwi', car: 'bmw', state: 'fl',
color: 'black', tree: 'elm', animal: 'rat', clothes: 'glove' }
]

最好的方法是什么?

最佳答案

[list.keys].product(list.values.transpose).map { |a| a.transpose.to_h }
#=> [{:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw",
# :state=>"la", :color=>"red", :tree=>"oak", :animal=>"cat",
# :clothes=>"tie"},
# {:letter=>"b", :number=>"two", :fruit=>"pear", :car=>"mb",
# :state=>"ny", :color=>"white", :tree=>"pine", :animal=>"dog",
# :clothes=>"sock"},
# {:letter=>"c", :number=>"three", :fruit=>"kiwi", :car=>"bmw",
# :state=>"fl", :color=>"black", :tree=>"maple", :animal=>"rat",
# :clothes=>"glove"}]

假设 list 定义如下。

list = {
letter: ['a', 'b' ],
number: ['one', 'two' ],
fruit: ['apple', 'pear'],
car: ['vw', 'mb' ]
}

步骤如下。

b = [list.keys]
#=> [[:letter, :number, :fruit, :car]]
c = list.values
#=> [["a", "b"], ["one", "two"], ["apple", "pear"], ["vw", "mb"]]
d = c.transpose
#=> [["a", "one", "apple", "vw"],
# ["b", "two", "pear", "mb"]]
e = b.product(d)
#=> [[[:letter, :number, :fruit, :car], ["a", "one", "apple", "vw"]],
# [[:letter, :number, :fruit, :car], ["b", "two", "pear", "mb"]]]
e.map { |a| a.transpose.to_h }
#=> [{:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw"},
# {:letter=>"b", :number=>"two", :fruit=>"pear", :car=>"mb"}]

让我们更仔细地看看最后一步。 mape 的第一个元素传递给 block 并将 block 变量 a 设置为其值:

a = e.first
#=> [[:letter, :number, :fruit, :car],
# ["a", "one", "apple", "vw"]]

区 block 计算如下。

f = a.transpose
#=> [[:letter, "a"], [:number, "one"], [:fruit, "apple"], [:car, "vw"]]
f.to_h
#=> {:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw"}

e.map { |a| 的剩余计算a.transpose.to_h } 类似。

关于arrays - 将散列转换为散列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905674/

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