Grab unique tuples in python list, irrespective of order

后端 未结 4 1775
予麋鹿
予麋鹿 2021-01-04 10:14

I have a python list:

[ (2,2),(2,3),(1,4),(2,2), etc...]

What I need is some kind of function that reduces it to its unique components... w

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-04 10:44

    set() will remove all duplicates, and you can then put it back to a list:

    unique = list(set(mylist))
    

    Using set(), however, will kill your ordering. If the order matters, you can use a list comprehension that checks if the value already exists earlier in the list:

    unique = [v for i,v in enumerate(mylist) if v not in mylist[:i]]
    

    That solution is a little slow, however, so you can do it like this:

    unique = []
    for tup in mylist:
        if tup not in unique:
            unique.append(tup)
    

提交回复
热议问题