Adjacent elements are a special kind of existence among non adjacent elements , So let's first discuss the deletion of the same elements that are not adjacent .
result :list=[1,2,3,4]
# The first one is
list = [1,2,3,3,4,1,1]
new_list = []
for i in list[:]:
if i not in new_list: # You can delete duplicate elements , Whether adjacent or not
new_list.append(i)
print(new_list)
# The second kind Set can be de duplicated First convert to set and then list
list = [1,2,3,3,4,1,1]
print(list(set(list)))
# The third kind of
list = [1,2,3,3,4,1,1]
list.sort()
new_list = []
for i in range(len(list) - 1):
if list[i] == list[i + 1]:
new_list.append(list[i + 1])
for j in new_list:
list.remove(j)
print(list)
# A fourth
# fromkeys Is to assign the same value to all the keys ( If no content is specified, the default assignment is None)
list = [1,2,3,3,4,1,1]
new_list = []
dct = dict.fromkeys(list)
# print(dct)
for n in dct:
new_list.append(n)
print(new_list)
# The fifth Abbreviation for the fourth method
list1 = [1,2,3,3,4,1,1]
print(list(dict.fromkeys(list1)))
# result :list1 = [1, 2, 3, 4, 1]
# The first one is , Compare two adjacent values , If the same , be del One of them , One by one , Until there's no repetition .
list1 = [1,2,2,3,3,4,1,1]
for i in range(len(list1) - 1, 0, -1):
if list1[i] == list1[i-1]:
del list1[i]
print(list1)
# The second kind , Use itertools library
import itertools
list1 = [1,2,2,3,3,4,1,1]
new_list1 = [k for k, g in itertools.groupby(list1)]
print(new_list1)
# The third kind of generator (generator)
# among del_adjacent() Is a generator type , Need to use list Convert to list
list1 = [1,2,2,3,3,4,1,1]
def del_adjacent(iterable):
prev = object()
for iterm in iterable:
if iterm != prev:
prev = iterm
yield iterm
a = list(del_adjacent(list1))
print(a)