Method of Python list to remove duplication and keep the original order unchanged
- 2021-10-24 23:15:57
- OfStack
code & & demo
Summarize
Background
python's weight removal operation is as fierce as a tiger, set list pulls down, and it is weight removal, but the order is disrupted. If there is no need for order, it really doesn't matter.
But if you need to keep the order, you need one small change.
code
&
&
demo
list is duplicated and the order is out of order
# normal Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print(l2)
# plus Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = {}.fromkeys(l1).keys()
After duplication removal, it is still the original list sequence
# normal Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
# plus Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)
Realization of writing loop code
# normal Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
# plus Writing style
l1 = ['b','c','d','b','c','a','a']
l2 = []
[l2.append(i) for i in l1 if not i in l2]
Implementation of writing while loop code
L = [3, 1, 2, 1, 3, 4]
T = L[:]
for i in L:
while T.count(i) > 1:
del T[T.index(i)]
T.sort(key=L.index)
lambda writing
Remarks:
ambda L, i: L if i in L L + [i] # Returns the list itself if the element is in the list, L + [i] if it is not [[],] + L # is equivalent to [[], L], which is convenient for later calculation
Summarize
If you struggle with spatial complexity, what do you do with python?
Let's talk about whether it can be completed first, and then talk about optimization.
The above is Python list deduplication and keep the original order of the method of the same details, more information about Python list deduplication please pay attention to other related articles on this site!