【问题标题】:Ruby sorting and eliminating duplicatesRuby 排序和消除重复项
【发布时间】:2011-12-10 07:38:36
【问题描述】:

我有一个列表,需要按最流行的元素进行排序。有没有办法做到这一点?

重新排序后,我还需要去掉重复的。我对此有一个功能的想法,但它似乎效率低下,那么有内置的方法可以帮助解决这个问题吗?

【问题讨论】:

    标签: ruby arrays list sorting methods


    【解决方案1】:
    [1,5,4,6,4,1,4,5].group_by {|x| x}.sort_by {|x,list| [-list.size,x]}.map(&:first)
    => [4,1,5,6]
    

    喜欢吗?

    【讨论】:

      【解决方案2】:

      Array#sort 方法采用可选谓词来比较两个元素,所以...

      list.sort { |a, b| a.popularity <=> b.popularity }
      

      要消除重复,请使用Array#uniq

      list.uniq
      

      将它们粘合在一起,

      list = list.sort { |a, b| a.popularity <=> b.popularity }.unique
      

      或者干脆

      list.sort! { |a, b| a.popularity <=> b.popularity }.uniq!
      

      【讨论】:

        【解决方案3】:

        遍历列表来构建映射item -&gt; number of times的哈希只需要访问列表的所有元素,然后对哈希的操作将是常数时间,所以O(n),看起来并不那么昂贵.

        【讨论】:

          【解决方案4】:

          uniq 方法采用一个块,因此您可以指定对象的哪个“属性”必须是 uniq。

          new_list = list.sort_by{|el| el.popularity}.uniq{|el| el.popularity}
          

          【讨论】:

            【解决方案5】:

            除了 Glenn Mcdonalds 之外,这些答案中的大多数对我都不起作用(直到我发布了这个答案) 我在这样的其他地方找到了我自己问题的答案

            list = [2,1,4,4,4,1] #for example
            count = Hash.new(0)
            list.each {|element| count[element] += 1} #or some other parameter than element
            list = list.uniq.sort {|x,y| count[y] <=> count[x]}
            

            【讨论】:

              猜你喜欢
              • 2011-02-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-05-10
              • 1970-01-01
              相关资源
              最近更新 更多