繁体   English   中英

如果存在于另一个列表中,python从嵌套列表中删除该元素+

[英]python remove element from nested list if it exists in another list +

可以说我有一个清单:

A = ['x', 'y', 'z']

另一个-嵌套:

B = [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c', 'z']]

我如何基于“ z”在A中并且子列表B的每个第一个元素[0]都在列表A中的知识,从列表B的最后一个子列表中删除“ z”?

所以基本上我需要从这样一个嵌套列表中删除所有元素,其中元素在A中,而它不在该嵌套列表的第一个位置?

我正在尝试这个,但要堆积:

for i in B:
    for j in i[1:]:
        if j in A:
            del j

但我缺少一些东西。

使用列表推导来就地更新列表:

for sublist in B:
    if sublist[0] in A:
        sublist[1:] = [v for v in sublist[1:] if v not in A]

循环中的j只是对子列表中值的另一个引用。 del j删除了该引用,但是列表仍然包含该引用。 您可以使用del listobj[index]listobj.pop(value)从列表中del listobj[index] listobj.pop(value) (注意细微的含义),但是如果不小心就从列表中进行迭代删除会导致跳过项目。

通过分配给切片,可以就地替换列表本身中的那些元素。

请注意,您可能想将A 设为 使用一组时,成员资格测试要快得多:

Aset = set(A)

for sublist in B:
    if sublist[0] in Aset:
        sublist[1:] = [v for v in sublist[1:] if v not in Aset]

演示:

>>> A = ['x', 'y', 'z']
>>> B = [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c', 'z']]
>>> Aset = set(A)
>>> for sublist in B:
...     if sublist[0] in Aset:
...         sublist[1:] = [v for v in sublist[1:] if v not in Aset]
...
>>> B
[['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c']]

您可以使用嵌套列表理解:

>>> [sub[:1]+[i for i in sub[1:] if not(sub[0] in A and i in A)] for sub in B]
[['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c']]

在这里,您将保留不符合删除条件的子列表中的项目(从第二个项目到最后一个项目)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM