我有一个清单
x=[1,2,0,0,0,3,0,0,0,0,0,4]
我想减去列表
y=[0,0,0]
来自清单x
所以结果应该是
z=[1,2,3,0,0,4]
我如何在python中实现这一目标? 编辑 - 请注意我不是要替换我试图删除
答案 0 :(得分:2)
在我看来,你需要寻找匹配的索引,然后使用切片赋值替换它们:
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)
答案 1 :(得分:0)
这是我的方法,找到x[0]
的索引列表,然后删除子列表。
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)
感谢@ mgilson,我修复了一个错误。
答案 2 :(得分: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)
答案 3 :(得分:0)
这是一种愚蠢的方式:
import json
xs = repr(x)[1:-1]
ys = repr(y)[1:-1]
new_x = json.loads((''.join(xs.split(ys))).replace(',,',','))