存储在列表中的过滤列表

Filter lists that are stored in a list

我有几个要过滤的列表。考虑以下示例:

a = [1,2]
b = [2,3]

l = [a,b]

for i in l:
  i = [elem for elem in l if elem != 2]

我希望输出为 a==[1]b==[3],但看起来 i 的更新不会更改元素 ab ].在 C++ 中,我会使用指针,但我似乎无法在 Python.

中找到相应的概念

通过在 for 循环中为 i 分配一个新列表,它会失去对 ab 的引用,因此它们不会得到更新。相反,您应该更新 i in-place。您还应该遍历 i 而不是 l 来过滤每个 sub-list:

for i in l:
    i[:] = (elem for elem in i if elem != 2)

演示:https://replit.com/@blhsing/BlissfulWhichGravity

你确定你不只是想要像下面这样的东西吗?

a = [1, 2]
b = [2, 3]

l = [[i for i in a if i != 2], [i for i in b if i != 2]]

或者更灵活:

exclude = (2,)

a = [1, 2]
b = [2, 3]

l = [a, b]
l = [[i for i in x if not any(i == e for e in exclude)] for x in l]

后一种方法使每个人都可以向 l 添加额外的子列表,并指定要从中排除的更多数字。

试试这个:

a = [1,2]
b = [2,3]

l = [a,b]

for i in l:
    i.remove(2)
  
print(a)
print(b)
print(l)

如果 2 出现不止一次,您可以尝试:

for i in l:
    try:
        while True:
            i.remove(2)
    except ValueError:
        pass
  

输出:

[1]
[3]
[[1], [3]]