Fastest way to get sorted unique list in python?

后端 未结 5 2018
谎友^
谎友^ 2021-02-01 06:16

What is the fasted way to get a sorted, unique list in python? (I have a list of hashable things, and want to have something I can iterate over - doesn\'t matter whether the lis

5条回答
  •  悲哀的现实
    2021-02-01 06:49

    Maybe this is not the answer you are searching for, but anyway, you should take this into your consideration.

    Basically, you have 2 operations on a list:

    unique_list = set(your_list)       # O(n) complexity
    sorted_list = sorted(unique_list)  # O(nlogn) complexity
    

    Now, you say "it seems to me that first checking for uniqueness and then sorting is wasteful", and you are right. But, how bad really is that redundant step? Take n = 1000000:

    # sorted(set(a_list))
    O(n) => 1000000
    o(nlogn) => 1000000 * 20 = 20000000
    Total => 21000000
    
    # Your fastest way
    O(nlogn) => 20000000
    Total: 20000000
    

    Speed gain: (1 - 20000000/21000000) * 100 = 4.76 %

    For n = 5000000, speed gain: ~1.6 %

    Now, is that optimization worth it?

提交回复
热议问题