What is the cleanest way to do a sort plus uniq on a Python list?

后端 未结 5 940
囚心锁ツ
囚心锁ツ 2020-12-23 15:55

Consider a Python list my_list containing [\'foo\', \'foo\', \'bar\'].

What is the most Pythonic way to uniquify and sort a list ?
(thi

5条回答
  •  庸人自扰
    2020-12-23 16:49

    The straightforward solution is provided by Ignacio—sorted(set(foo)).

    If you have unique data, there's a reasonable chance you don't just want to do sorted(set(...)) but rather to store a set all the time and occasionally pull out a sorted version of the values. (At that point, it starts sounding like the sort of thing people often use a database for, too.)

    If you have a sorted list and you want to check membership on logarithmic and add an item in worst case linear time, you can use the bisect module.

    If you want to keep this condition all the time and you want to simplify things or make some operations perform better, you might consider blist.sortedset.

提交回复
热议问题