簡體   English   中英

按二級數組中鍵的順序對哈希排序

[英]Sort hash by order of keys in secondary array

我有一個哈希:

hash = {"a" => 1, "b" =>2, "c" => 3, "d" => 4}

我有一個數組:

array = ["b", "a", "d"]

我想創建一個新數組,該數組由與原始哈希鍵相對應的原始哈希值組成,這些哈希鍵也可以在原始數組中找到,同時保持原始數組的順序。 所需的數組為:

desired_array = [2, 1, 3]

這里的想法是采用單詞“ bad”,為字母分配數字,然后按該順序排列與“ b”,“ a”和“ d”相對應的數字數組。

由於您的問題尚不清楚,因此我假設您希望將desired_array設為一個數組(您說您想要一個新的數組並以新的哈希值結束句子)。 同樣在您的示例中,我假設您希望對['b','a','d']的期望的array為[2,1,4],對於['b','的期望為[2,1,3] a','c']。

您應該只使用Enumerable#map方法來創建一個將第一個數組映射到所需數組的數組,如下所示:

desired_array = array.map { |k| hash[k] }

您應該熟悉Enumerable#map方法,這是非常方便的方法。 從rubydocs中獲取該方法:為枚舉中的每個元素返回一個新的數組,其中包含運行塊一次的結果。 因此,在這種情況下,我們將遍歷數組並調用hash [k]從哈希中選擇值,並創建一個由哈希選擇的值的新數組。 由於迭代是有序的,因此您將保留原始序列。

我將使用Enumerable#map然后使用Enumerable#sort_by例如

hash = {"d" => 4, "b" =>2, "c" => 3, "a" => 1}
order = ["b", "a", "d"]

# For each key in order, create a [key, value] pair from the hash.
# (Doing it this way instead of filtering the hash.to_a is O(n) vs O(n^2) without
#  an additional hash-probe mapping. It also feels more natural.)
selected_pairs = order.map {|v| [v, hash[v]]}
# For each pair create a surrogate ordering based on the `order`-index
# (The surrogate value is only computed once, not each sort-compare step.
#  This is, however, an O(n^2) operation on-top of the sort.)
sorted = selected_pairs.sort_by {|p| order.find_index(p[0]) }

p sorted

# sorted =>
# [["b", 2], ["a", 1], ["d", 4]]

我一直沒有接通結果返回到一個哈希,因為我是哈希應該被視為具有任何種類的順序,除了調試工具的信仰。 (請記住,Ruby 2哈希是按插入順序排序的。)

您需要的只是values_at

hash.values_at *array

數不清的方法圖,每種方法都很完美
wanted_array = array.map {| k | hash [k]}或期望數組= array.each {| k | 哈希[k]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM