In the interview process of the Python-related position, the list of lists will be inspected. (Note that it is sometimes required to ensure that the order of the heavy )
1. Intuitive method
1 li=[1,2,3,4,5,1,2,3]2 new_li=[]3 for in Li: 4 if not in new_li:5 new_ Li.append (i)6print(new_li)
First create a new empty list, by traversing the original list, and then using the logical relationship not in to come and go heavy.
Summary: This can be done, but the process is not simple enough. However, this method guarantees the order of the list.
2, the use of Set automatic weight function
1 li=[1,2,3,4,5,1,2,3]2 li=list (set (LI))3print(LI)
Convert a list to a collection and convert it to a list, taking advantage of the auto-redo function of the collection. Simple and fast. The disadvantage is that using the Set method does not guarantee the order of the go-back.
However, you can ensure that the order of the de-weight is unchanged by using the index method in the list.
1 li=[1,2,3,4,5,1,2,3]2 new_li=list (set (LI))3 new_li.sort (key= Li.index)4print(new_li)
The above two list de-weight methods are commonly used to go to the weight of the method, it should be noted that the interview if the order to ensure the list, note that the set method through the index can also guarantee the order.
Several ways to remove the list in Python for Python common face question