Remove items from the list immediately before a specific item

Let's say I have a list like:

a = ['no', 'no', 'no', 'yes', 'no', 'yes', 'no']

Here I want to delete everyone 'no'that is preceded by everything'yes' . Therefore, my resulting list should look like :

['no', 'no', 'yes', 'yes', 'no']

I found that to remove an item from the list by its value, we can use list.remove(..)as:

a = ['no', 'no', 'no', 'yes', 'no', 'yes', 'no']
a.remove('no')
print a

But this gives me the result with removing the first appearance 'no'like:

['no', 'no', 'yes', 'no', 'yes', 'no']

How can I achieve the desired result by removing all occurrences 'no'that are preceded by everything 'yes'on my list?

+6
source share
5 answers

Try the following:

a = ['no', 'no', 'no', 'yes', 'no', 'yes', 'no']
a = ' '.join(a)  
print(a.replace('no yes', 'yes').split(' '))

: 1. ' '.join() 2. " " "" a.replace() 3. a.split(' ')

+4

'no', 'yes' , itertools.zip_longest(...) Python 3.x( iterools.izip_longest(..) Python 2.x) ( fillvalue None), :

>>> a = ['no', 'no', 'no', 'yes', 'no', 'yes', 'no']

# Python 3.x solution
>>> from itertools import zip_longest
>>> [x for x, y in zip_longest(a, a[1:]) if not(x=='no' and y=='yes')]
['no', 'no', 'yes', 'yes', 'no']

# Python 2.x solution
>>> from itertools import izip_longest
>>> [x for x, y in izip_longest(a, a[1:]) if not(x=='no' and y=='yes')]
['no', 'no', 'yes', 'yes', 'no']

zip_longest , :

, . , fillvalue. , .

+12

Iterate with the condition and add the last element:

[i for i, j in zip(a, a[1:]) if (i == 'yes' or j == 'no')] + a[-1:]
+4
source

An interesting roundabout using regexwith look-ahead:

>>> import re
>>> s = ' '.join(a)                          # convert it into string
>>> out = re.sub('no (?=yes)', '', s)        # remove
>>> out.split()                              # get back the list
=> ['no', 'no', 'yes', 'yes', 'no']
+3
source

Try this code!

I also added a screenshot of the exit!

a = ['no', 'no', 'no', 'yes', 'no', 'yes', 'no']
for i in range (1,5):
  if a[i]=='yes':
    j=i-1
    a.pop(j)

print(a)

Exit:

enter image description here

0
source

All Articles