How to remove duplicate items from a list using list comprehension?

前端 未结 7 1095
庸人自扰
庸人自扰 2020-11-30 11:43

How to remove duplicate items from a list using list comprehension? I have following code:

a = [1, 2, 3, 3, 5, 9, 6, 2, 8, 5, 2, 3, 5, 7, 3, 5, 8]
b = []
b =         


        
7条回答
  •  醉梦人生
    2020-11-30 12:00

    >>> from itertools import groupby
    >>> repeated_items = [2,2,2,2,3,3,3,3,4,5,1,1,1]
    >>> [
    ...     next(group)
    ...     for _, group in groupby(
    ...         repeated_items,
    ...         key=lambda x: repeated_items.index(x)
    ...     )
    ... ]
    [2, 3, 4, 5, 1]
    

提交回复
热议问题