用另一个lis删除列表中的元素

2024-05-17 19:43:53 发布

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

我想知道如何使用另一个列表来消除列表中的元素。 例如,假设我有:

eliminate([['dog', 'cat'], ['cat', 'fish'], ['dog', 'hamster]], ['dog', 'cat'])
[[], ['fish'], ['hamster]]

我尝试遍历子列表的所有元素,并检查它们是否在第二个列表中,以将它们删除,但得到的列表与原始列表相同。 任何帮助都会很好

def eliminate(ballots, to_eliminate):

    for sublist in ballots:

        for elem in sublist:

            if elem in to_eliminate:
                ballots.pop(sublist.index(elem))
    return ballots

Tags: toin元素列表forifdefcat
2条回答

如果可以返回新列表

def eliminate(ballots, to_eliminate):
    ballots_n = []
    for sublist in ballots:
        temp_list = []
        for elem in sublist:
            if not elem in to_eliminate:
                temp_list.append(elem)
        ballots_n.append(temp_list)
    return ballots_n

学会使用print语句来调试你的程序,如果你没有尝试的话。例如:

def eliminate(ballots, to_eliminate):

    for sublist in ballots:

        for elem in sublist:

            if elem in to_eliminate:
                print("\nsublist=", sublist, "\telem=", elem)
                print("to_eliminate", to_eliminate)
                print("index", sublist.index(elem))
                ballots.pop(sublist.index(elem))
                print("ballots", ballots)
    return ballots

result = eliminate([['dog', 'cat'], ['cat', 'fish'], ['dog', 'hamster']], ['dog', 'cat'])
print(result)

输出:

sublist= ['dog', 'cat']     elem= dog
to_eliminate ['dog', 'cat']
index 0
ballots [['cat', 'fish'], ['dog', 'hamster']]

sublist= ['dog', 'cat']     elem= cat
to_eliminate ['dog', 'cat']
index 1
ballots [['cat', 'fish']]
[['cat', 'fish']]

这很清楚地表明了你的问题

确定消除元素dog位于该子列表的位置0处的一个子列表中。通过删除ballots[0],而不是您标识的元素来处理这个问题。修复pop引用

其次,您跳过ballots中的子列表,因为您在遍历列表时正在更改它。相反,创建一个只包含要保留的元素的新列表。这是许多语言中的一个常见错误,在这里的堆栈溢出中有几个重复的错误

相关问题 更多 >