30, "wanted"=>27, "second"=>45, "subject"=-6ren">
gpt4 book ai didi

ruby 哈希将值从一个键交换到另一个键

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:55 24 4
gpt4 key购买 nike

有没有人对我如何将散列中的值重新映射到不同的键有 Ruby 的建议?说我有这个

from => {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85} 

并且想要得到这个(即,“present”、“first”和“subject”、“second”的值已经交换):

to => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}

我想对大型数据集执行此操作。

最佳答案

# this is your starting hash:
from = {"first"=>30, "wanted"=>27, "second"=>45, "subject"=>68, "present"=>85}
# this is your replacement mapping:
map = {'present' => 'first', 'subject' => 'second'}
# create complete map by inverting and merging back
map.merge!(map.invert)
# => {"present"=>"first", "subject"=>"second", "first"=>"present", "second"=>"subject"}
# apply the mapping to the source hash:
from.merge(map){|_, _, key| from[key]}
# => {"first"=>85, "wanted"=>27, "second"=>68, "subject"=>45, "present"=>30}

关于ruby 哈希将值从一个键交换到另一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6937352/

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