Python–删除交替的连续重复项

2021年4月24日13:10:30 发表评论 756 次浏览

给定元素列表, 请删除元素的交替连续重复项。

输入:test_list = [5、5、5、5、6、6]
输出:[5、5、6]
说明:备用occ。 5和6中的一个被删除。
输入:test_list = [5, 5, 5, 5]
输出:[5, 5]
说明:备用occ。 5个被删除。

方法:使用循环+ remove()

以上功能的组合可用于解决此问题。在此, 我们迭代每个元素并使用其他先前的元素变量来跟踪替代条件。使用remove()执行删除。

Python3

# Python3 code to demonstrate working of 
# Remove alternate consecutive duplicates
# Using loop + remove()
  
# initializing lists
test_list = [ 5 , 5 , 5 , 5 , 6 , 6 , 8 , 3 , 3 , 8 ]
  
# printing original list
print ( "The original list : " + str (test_list))
  
# Using loop to iterate through elements
# element to keep track
temp = test_list[ 0 ]
count = 0
org_list = test_list
idx = 0
while ( 1 ):
      
     # break when idx greater than size
     if idx> = len (org_list):
         break
      
     # check for alternates 
     if count % 2 and temp = = test_list[idx]:
         test_list.remove(test_list[idx])
         idx = idx - 1
         count + = 1
         temp = test_list[idx]
     else :
          
         # keeping track of alternate index increment
         # and assignment
         if temp ! = test_list[idx]:
             count = 1
             temp = test_list[idx]
         else :
             count + = 1
     idx = idx + 1
  
# printing result 
print ( "List after alternate duplicates removal : " + str (test_list))

输出如下

The original list : [5, 5, 5, 5, 6, 6, 8, 3, 3, 8]
List after alternate duplicates removal : [5, 5, 6, 8, 3, 8]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: