[Turn] list are several ways to go heavy

Method a: The method of using the built-in set come weight

>>> lst1 = [2, 1, 3, 4, 1]
>>> lst2 = list(set(lst1))
>>> print(lst2)
[1, 2, 3, 4]

Method two: Use dictionary fromkeys () method come weight

>>> lst1 = [2, 1, 3, 4, 1]
>>> lst2 = {}.fromkeys(lst1).keys()
>>> print(lst2)
dict_keys([2, 1, 3, 4])

Method three: weight using conventional methods come

>>> lst1 = [2, 1, 3, 4, 1]
>>> temp = []
>>> for item in lst1:
        if not item in temp:
            temp.append(item)   
>>> print(temp)
[2, 1, 3, 4]

Method 4: Use come derived heavy listing

>>> lst1 = [2, 1, 3, 4, 1]
>>> temp = []
>>> [temp.append(i) for i in lst1 if not i in temp]
[None, None, None, None]
>>> print(temp)
[2, 1, 3, 4]

Method five: using sort function come weight

>>> lst1 = [2, 1, 3, 4, 1]
>>> lst2.sort(key=lst1.index)
>>> print(lst2)
[2, 1, 3, 4]

Six: sorted using a weight function come

>>> lst1 = [2, 1, 3, 4, 1]
>>> lst2 = sorted(set(lst1), key=lst1.index)
>>> print(lst2)
[2, 1, 3, 4]

Note: Several methods foregoing, there are several whose order is not guaranteed, such as a set () function to process!

If you want to delete duplicate items in the list in the list, you can also use the following methods to handle

>>> # 方法一:
>>> data = [2, 1, 3, 4, 1]
>>> [item for item in data if data.count(item) == 1]
[2, 3, 4]
>>> # 方法二:
>>> data = [2, 1, 3, 4, 1]
>>> list(filter(lambda x:data.count(x) == 1, data))
[2, 3, 4]

Guess you like

Origin www.cnblogs.com/everfight/p/10956159.html