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

时间:2019-09-19 14:02:14

标签: python-3.x list nested-lists

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

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

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

该函数应删除包含给定number的所有嵌套列表,并删除嵌套列表中的负数 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并运行代码。

  • 第一个for循环将删除包含给定数字的所有嵌套列表,并将获得以下内容:

    self.temp = [[-5, -1], [5, -1]]

    clist = [[-5, -1], [1, -5], [5, -1]]

  • 第二个for循环应删除嵌套列表中的所有否定number,但我们得到以下信息:

    self.temp = [[-5], [5]]

    clist = [[-5], [1, -5], [5]]

当我在第二个clist循环中工作时,尤其是在for列表中工作时,为什么self.temp会受到影响?它应该不参考原始列表,但是我遗漏了一些东西。救命?

1 个答案:

答案 0 :(得分:1)

似乎最容易理解嵌套列表:

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添加回参数之后),但是我不清楚您的实际意图是将结果保存到是否反对。