【问题标题】:Nested lists - Remove given element within nested lists嵌套列表 - 删除嵌套列表中的给定元素
【发布时间】:2019-09-19 14:02:14
【问题描述】:

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

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

【问题讨论】:

  • 你能给出完整的代码吗
  • @hsnsd 不幸的是,没有,因为这是我的任务的一部分。但我可以告诉你其他可能会影响的部分,但到目前为止,这是影响我结果的部分。

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


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

【讨论】:

  • 谢谢,成功了。没有必要保存结果。我不明白的一件事是,为什么从第二个for 循环中删除self.temp 中的元素时,它也会影响clist。
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
相关资源
最近更新 更多