l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
for el in l1:
if l1.count(el) > 1:
l1.remove(el)
print(l1)# Missing deletion , Because after deleting an element , The following elements are filled forward , Causes the next element to be skipped .
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
for el in range(len(l1)): # here len(l1) It has been determined that , Not as l1 Change with the following changes
if l1.count(l1[el]) > 1:
l1.remove(l1[el])
print(l1) # Will report a mistake , Because deleting an element results in l1 The length of is shorter , however for Traversing the previous index length , This will cause an error when the index exceeds the range
'''
No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :725638078
Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book !
'''
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
for el in l1[:]:
if l1.count(el) > 1:
l1.remove(el) # No problem , You can get rid of it , But you can't keep the original order
print(l1)
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
lst = []
for el in l1:
if lst.count(el) < 1:
lst.append(el)
print(lst) # No problem , It can also keep the original order , But a new list is created
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
for el in range(len(l1)-1, -1, -1):
if l1.count(l1[el]) > 1:
l1.pop(el) # No problem , And keep the original order
# l1.remove(l1[el]) # No problem , But you can't keep the original order
# del l1[el] # This will preserve the original order , You can think about why
print(l1)
'''
No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :725638078
Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book !
'''
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
def set_lst(lst):
for el in lst:
if lst.count(el) > 1:
lst.remove(el)
set_lst(lst) # Open a new function each time , Determine the list after an element was deleted last time
else: # Until the last , The elements in the list are all one , It's running else
return lst
print(set_lst(l1)) # Because it was deleted from the front , So do not keep the original order
'''
[1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 3, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 3, 3, 6, 6, 5, 5, 2, 2]
[1, 3, 6, 6, 5, 5, 2, 2]
[1, 3, 6, 5, 5, 2, 2]
[1, 3, 6, 5, 2, 2]
[1, 3, 6, 5, 2] return lst = [1, 3, 6, 5, 2]
'''
l1 = [1, 1, 2, 2, 3, 3, 3, 3, 6, 6, 5, 5, 2, 2]
lst = list(set(l1))
print(lst)
At the end, I recommend a very good learning tutorial , I hope to learn from you Python To be helpful to !
Python Basic introductory tutorial recommended
Python Crawler case tutorial