[英]python remove element from nested list if it exists in another list +
lets say I have a list: 可以说我有一个清单:
A = ['x', 'y', 'z']
and another one - nested: 另一个-嵌套:
B = [['x', 'a', 'b', 'c'], ['y', 'c'], ['x', 'a', 'c', 'z']]
how can I remove 'z' from the last sublist in list B based on the knowledge that 'z' is in A and also every first element [0] of the sublist B is in list A ? 我如何基于“ z”在A中并且子列表B的每个第一个元素[0]都在列表A中的知识,从列表B的最后一个子列表中删除“ z”?
so basically i need to detele all elements from such a nested list where element is in A and where it not stands in the first position of that nested list ? 所以基本上我需要从这样一个嵌套列表中删除所有元素,其中元素在A中,而它不在该嵌套列表的第一个位置?
I am trying this but get stacked: 我正在尝试这个,但要堆积:
for i in B:
for j in i[1:]:
if j in A:
del j
but I am missing something. 但我缺少一些东西。
Use a list comprehension to update a list in-place: 使用列表推导来就地更新列表:
for sublist in B:
if sublist[0] in A:
sublist[1:] = [v for v in sublist[1:] if v not in A]
j
in your loop is only another reference to a value in a sublist. 循环中的
j
只是对子列表中值的另一个引用。 del j
removes that one reference, but the list still contains that reference. del j
删除了该引用,但是列表仍然包含该引用。 You can remove values from the list with del listobj[index]
or listobj.pop(value)
(watch for subtleties in what those mean), but deleting from a list while iterating over it will result in items being skipped if you are not careful. 您可以使用
del listobj[index]
或listobj.pop(value)
从列表中del listobj[index]
listobj.pop(value)
(注意细微的含义),但是如果不小心就从列表中进行迭代删除会导致跳过项目。
By assigning to a slice, you replace those elements in the list itself, in-place. 通过分配给切片,可以就地替换列表本身中的那些元素。
Note that you probably want to make A
a set ; 请注意,您可能想将
A
设为一组 ; membership testing is far faster when using a set: 使用一组时,成员资格测试要快得多:
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]
Demo: 演示:
>>> 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']]
You can use a nested list comprehension: 您可以使用嵌套列表理解:
>>> [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']]
Here you'll preserve the items from sublists (from second item to end) that doesn't met your conditions for deleting. 在这里,您将保留不符合删除条件的子列表中的项目(从第二个项目到最后一个项目)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.