简体   繁体   中英

Python remove specific adjacent duplicates from list

I have a list 

x=['b1','00','00','10','10','F5','D1','01','01'...]  # sample data

I am trying to remove duplicates of '10' only when they are adjacent.

Till now I have tried

my_list= [x[i] for i in range(len(x)) if (i==0) or ( x[i] !=x[i-1])] # current implementation 

This removes all adjacent duplicates but I want to keep '00','00' and '01' and just remove duplicates of '10'

How do I achieve this using a list comprehension?

Just add an extra condition to your list comprehension: or (x[i] != '10') .

[x[i] for i in range(len(x)) if (i==0) or (x[i] !=x[i-1]) or (x[i] != '10')]
# ['b1', '00', '00', '10', 'F5', 'D1', '01', '01']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM