程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python removes adjacent and non adjacent identical elements from the list

編輯:Python

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 .

Deletion of non adjacent elements

 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)))

Deletion of adjacent elements

# 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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved