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

后端 未结 5 935
囚心锁ツ
囚心锁ツ 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:44

    Others have mentioned sorted(set(my_list)), which works for hashable values such as strings, numbers and tuples, but not for unhashable types such as lists.

    To get a sorted list of values of any sortable type, without duplicates:

    from itertools import izip, islice
    def unique_sorted(values):
        "Return a sorted list of the given values, without duplicates."
        values = sorted(values)
        if not values:
            return []
        consecutive_pairs = izip(values, islice(values, 1, len(values)))
        result = [a for (a, b) in consecutive_pairs if a != b]
        result.append(values[-1])
        return result
    

    This can be further simplified using the "pairwise" or "unique_justseen" recipes from the itertools documentation.

提交回复
热议问题