如何从列表中删除值,以及如何从另一个列表中删除同一位置的值

2024-03-29 13:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个列表:

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

y=[e,r,g,d,e,w,t,y,t,r]

我想从“x”列表中删除所有零,所有值都对应于“y”列表中零的位置,这样最后:

x=[1,3,2,5,6,4,2]

y=[e,d,e,w,t,t,r]

我试过:

for i in range(len(x)):
    if x[i]==0:
        del x[i]
        del y[i]
return x
return y

但是,我意识到,随着第I个索引位置中的元素被删除,范围也会发生变化。有没有更好的循环或方法我可以实现。你知道吗


Tags: 方法in元素列表forlenreturnif
3条回答

您可以构造新列表,而不是删除:

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

y = 'e,r,g,d,e,w,t,y,t,r'.split(',')

x, y = zip(*[
    (xe, ye)
    for xe, ye in zip(x, y)
    if xe != 0
])

print(x, y)

啊哈,我花了很长时间想在我需要的时候弄清楚。很高兴你不用经历。你知道吗

def list_del(inp,poss):
'''delete items at indexes given in the list poss from list inp'''
try:
    assert(isinstance(inp,list))
except AssertionError:
    raise(AssertionError('input has to be a list, if numpy, using np.delete'))
inpu = inp

pos = 0
for i in list(sorted(poss)):
    del inpu[i-pos]
    pos += 1
return inpu

示例:

list_del([0,1,2,3,4],[0,2,-1])

退货

[1, 2]

就你而言:

for i in list(x):
    if i == 0:
        deleting.append(i)
list_del(x,deleting)
list_del(y,deleting)

问题是,当您从列表中删除一个元素时,所有后面的索引都会向后移动1,这样您删除的内容就不会留下任何间隙。但是,早期的索引保持不变;因此简单的解决方法是向后迭代索引。你知道吗

def remove_zeros(x, y):
    for i in reversed(range(len(x))):
        if x[i] == 0:
            del x[i]
            del y[i]
    return x, y

请注意,如果要返回两个结果,则必须将它们作为元组返回;否则将无法到达第二个return语句。你知道吗

相关问题 更多 >