如何根据数组键来排序哈希键?

huangapple go评论61阅读模式
英文:

How to sort hash keys based on array keys?

问题

这是一个哈希的示例:

h1 = {
  a1: :a2,
  b1: :b2,
  c1: :c2,
  d1: :d2,
  e1: :e2,
  f1: :f2
}

还有这样一个键的数组:

a1 = [:b1, :d1, :f1]

如何根据数组对此哈希的键进行排序?不在数组中的哈希键必须按它们原来的顺序排列在已排序的键后面。

结果:

{
  b1: :b2,
  d1: :d2,
  f1: :f2,
  a1: :a2,
  c1: :c2,
  e1: :e2
}
英文:

There is an example of a hash:

h1 = {
  a1: :a2,
  b1: :b2,
  c1: :c2,
  d1: :d2,
  e1: :e2,
  f1: :f2
}

And there is such an array of keys:

a1 = [:b1, :d1, :f1]

How to sort the keys of this hash based on the array? The hash keys that are not in the array must come after the sorted ones in the order in which they were.

Result:

{
  b1: :b2,
  d1: :d2,
  f1: :f2,
  a1: :a2,
  c1: :c2,
  e1: :e2
}

答案1

得分: 7

Hash#slice 方法按照 a1 中定义的顺序返回 h1 中的元素。而 Hash#except 方法返回不在 a1 中的元素。最后,Hash#merge 方法将这两组元素合并成一个哈希表。

英文:

I would do this:

h1.slice(*a1).merge(h1.except(*a1))
#=> {:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}

Hash#slice returns the elements from h1 in the order how they are defined in a1. And the Hash#except returns the missing ones. And Hash#merge merges both groups into one hash.

答案2

得分: 4

You may write

h1.slice(*a1, *(h1.keys - a1))

or

h1.slice(*a1, *h1.keys)

Both return

{:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}

See Hash#slice.

英文:

You may write

h1.slice(*a1, *(h1.keys - a1))

or

h1.slice(*a1, *h1.keys)

Both return

{:b1=>:b2, :d1=>:d2, :f1=>:f2, :a1=>:a2, :c1=>:c2, :e1=>:e2}

See Hash#slice.

huangapple
  • 本文由 发表于 2023年5月7日 20:58:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定