0

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

[[-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

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

  • 第一个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列表时?它应该没有参考原始列表,但我遗漏了一些东西。帮助?

4

1 回答 1

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

于 2019-09-19T14:18:35.410 回答