嵌套列表 - 删除嵌套列表中的给定元素

Nested lists - Remove given element within nested lists

我们有以下列表作为输入:

[[-5, -1], [1, -5], [5, -1]]

我创建了一个函数,它将 clist 作为列表,number 是我想从列表中删除的随机数。

该函数应删除所有包含给定 number 的嵌套列表,并删除嵌套列表

中的 negative number
def reduce(self, clist, number):
    self.temp = list(clist)

    # remove the nested list that contain the given number
    for item in clist:
        if number in item:
            self.temp.remove(item)

    # remove the negative number within the nested list
    for obj in self.temp:
        try:
            obj.remove(-number)
        except:
            pass

    return self.temp

让我们选择 1 作为 number 和 运行 代码。

我不明白为什么 clist 在我处理第二个 for 循环时受到影响,尤其是在我处理 self.temp 列表时?它应该没有参考原始列表,但我遗漏了一些东西。帮助?

似乎嵌套列表理解最简单:

def reduce(clist, number):
    return [[x for x in subl if x != -number] for subl in clist if number not in subl]

print(reduce([[-5, -1], [1, -5], [5, -1]], 1))
# [[-5], [5]]

这会在不包含 number 的列表上迭代两次,因此一个稍微更有效的解决方案将是,但实际速度将取决于您的数据。

def reduce(clist, number):
    result = []
    for subl in clist:
        temp = []
        for x in subl:
            if x == number:
                break
            elif x != -number:
                temp.append(x)
        else:
            result.append(temp)  # Only happens if there was no break
    return result

如果需要,您可以将此结果保存到 self.temp(在将 self 添加回参数后),但我不清楚您的实际意图是否是保存结果对象与否。