0

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

  • 3
    Possible duplicate of [Replacing a sublist with another sublist in python](http://stackoverflow.com/questions/12898023/replacing-a-sublist-with-another-sublist-in-python) – Peter Gibson Mar 07 '17 at 04:16

4 Answers4

2

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)
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

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.

McGrady
  • 10,869
  • 13
  • 47
  • 69
  • 1
    For what it's worth, this doesn't actually work... Try it with `x=[1, 2, 0, 1, 2, 0]; y=[1, 2, 0]`. The result _should_ be `[]`, but instead you get `[1, 2, 0]`. The reason is because after you perform the first slice assignment, the list is now shorter and the indexes that you saved in the first pass no longer work. You can fix it by adding a `reversed` call around your list-comprehension though... – mgilson Mar 07 '17 at 19:03
  • @mgilson thanks for your reminding,you're right,I fixed it. – McGrady Mar 08 '17 at 02:57
0
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)
user82395214
  • 829
  • 14
  • 37
0

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(',,',','))
pjz
  • 41,842
  • 6
  • 48
  • 60