说我给了一个字符串数组,每个字符串都有一个相应的权重。例如:
str_arr = ["james", "blake", "rob"]
weights = [4, 7, 1]
str_arr [i]对应权重[i]。
我如何按权重按升序排序str_arr?例如:
(排序后)权重为[1, 4, 7]
,对应于str_arr = ["rob", "james", "blake"]
我如何获得["rob", "james", "blake"]
?
大多数排序比较器处理修改当前数组上排序的工作方式,我研究了关于不同数组的现有顺序的排序 - 但我不确定如何对整数数组进行排序并基于整数数组的输出同时对str_arr执行相同的操作......是否有Rubyist方式这样做?
答案 0 :(得分:2)
您可以使用sort_by
和with_index
:
(rdd
# Split by "|" and then for each item by ":"
.map(lambda xs: [x.split(":")[1] for x in xs.split("|")])
# Convert to tuple
.map(tuple)
.toDF(["key1", "key2", "key3"]))
答案 1 :(得分:1)
您可以使用并行分配执行以下操作:
str_arr, weights = str_arr.zip(weights).sort_by(&:last).transpose
#=> [["rob", "james", "blake"], [1, 4, 7]]
str_arr #=> ["rob", "james", "blake"]
weights #=> [1, 4, 7]
答案 2 :(得分:1)
str_arr.values_at(*weights.size.times.sort_by { |i| weights[i] })
#=> ["rob", "james", "blake"]
这两个步骤如下。
a = weights.size.times.sort_by { |i| weights[i] }
#=> [2, 0, 1]
str_arr.values_at(*a)
#=> ["rob", "james", "blake"]
答案 3 :(得分:1)
如果您有两个100%相互链接的阵列,则应使用哈希:
str_arr = ["james", "blake", "rob"]
weights = [4, 7, 1]
weights = str_arr.zip(weights).to_h
# {"james"=>4, "blake"=>7, "rob"=>1}
您可以按以下方式排序_by值:
str_arr = ["james", "blake", "rob"]
weights = [4, 7, 1]
weights = str_arr.zip(weights).to_h
p weights.sort_by{|k, v| v}.map(&:first)
#=> ["rob", "james", "blake"]