Varun Mallya
Varun Mallya

Reputation: 33

delete a complete list from another list in python

I have a list

x=[1,2,0,0,0,3,0,0,0,0,0,4]

I want to subtract the list

y=[0,0,0]

from list x

So the result should be

z=[1,2,3,0,0,4]

How can i achieve this in python? EDIT-Please note i am not trying to replace i am trying to delete

Upvotes: 0

Views: 101

Answers (4)

McGrady
McGrady

Reputation: 11477

This is my way,find the index list of x[0],and remove the sublist.

x=[1,2,0,0,0,3,0,0,0,0,0,4]
y=[0,0,0]


def sub(x, y):
    for i in [index for index, value in enumerate(x) if value == y[0]]:
        if x[i:i + len(y)] == y:
            x[i:i + len(y)] = [None] * len(y)

    return filter(lambda k: k != None, x)


print sub(x,y)

Thanks to @mgilson,I fixed a bug.

Upvotes: 0

pjz
pjz

Reputation: 43067

Here's a hacky way to do it:

import json

xs = repr(x)[1:-1]
ys = repr(y)[1:-1]

new_x = json.loads((''.join(xs.split(ys))).replace(',,',','))

Upvotes: 0

user82395214
user82395214

Reputation: 929

x=[1,2,0,0,0,3,0,0,0,0,0,4]
y=[0,0,0]
z = []

foundForThisPass = False
indexsSame = []

for a in range (0, len(y)):
  for b in range(0, len(x)):
    if (y[a] == x[b] and foundForThisPass == False):
      indexsSame.append(b)
      foundForThisPass = True

  foundForThisPass = False


i = 0
for a in range (0, len(x)):
  if (a == indexsSame[i]):
    i += 1
  else:
    z.append(x[a])

print(z)

Upvotes: 0

mgilson
mgilson

Reputation: 309969

It looks to me like you'll need to look for the matching indices and then replace them with nothing using slice assignment:

x=[1,2,0,0,0,3,0,0,0,0,0,4]
y=[0,0,0]

# Search for all non-overlapping occurences of `y`
ix = 0
matches = []
while ix < len(x):
    if x[ix:ix + len(y)] == y:
        matches.append(ix)
        ix += len(y)
    else:
        ix += 1

# Replace them with slice assignment.
for ix in reversed(matches):
    x[ix:ix + len(y)] = []

print(x)

Upvotes: 2

Related Questions