简体   繁体   English

根据另一个列表从子列表中删除元素

[英]Remove element from sublist according to another list

I have a list filled with sublist:我有一个充满子列表的列表:

a = [['12345/0111','57894/0311','45698/2333'],['12345/0600','87456/1234']]

Then I have another list:然后我有另一个清单:

b = ['0111','0600','0311']

I would like to delete all elements from list a which doesn't contain elements from list b .我想删除列表a中不包含列表b 中的元素的所有元素。 I thought that it should be like this for the firts element in b (in this case 45698/2333 and 87456/1234):我认为b 中的 firts 元素应该是这样的(在本例中为 45698/2333 和 87456/1234):

for x in a:
    for y in x:
        if b[0] not in y:
            x.remove(y)

But it doesn't work even for the first element and I really don't know how to do it for all the elements in b .但它甚至对第一个元素也不起作用,我真的不知道如何对b 中的所有元素执行此操作。

EDIT: I am sorry I didn't specified that in the output I need to have the same nested list structure.编辑:对不起,我没有在输出中指定我需要具有相同的嵌套列表结构。

Give this a try:试试这个:

# create a new list to store values
c = []

for x in a:
   for y in x:
      if str.split(y, '/')[1] in b:
         c.append(y)

My Results:我的结果:

a
[['12345/0111', '57894/0311', '45698/2333'], ['12345/0600', '87456/1234']]
b
['0111', '0600', '0311']
c = []
for x in a:
    for y in x:
       if str.split(y, '/')[1] in b:
          c.append(y)

c
['12345/0111', '57894/0311', '12345/0600']

EDITED AFTER OP CLARIFICATION: OP 澄清后编辑:

for x in a:
  for y in x:
    if str.split(y, '/')[1] in b:
      x.remove(y)

EDITED RESULTS:编辑结果:

for x in a:
   for y in x:
     if str.split(y, '/')[1] in b:
       x.remove(y)

a
[['57894/0311', '45698/2333'], ['87456/1234']]

You're saying to remove anything that's in b, which doesn't appear to be what you mean.您是说要删除 b 中的任何内容,这似乎不是您的意思。 In any case if you remove the 'not' from either of the following two samples they will give you the ones that are in b.在任何情况下,如果您从以下两个示例中的任何一个中删除“not”,它们都会为您提供 b 中的那些。

a = [['12345/0111','57894/0311','45698/2333'],['12345/0600','87456/1234']]
b = ['0111','0600','0311']

Not Nested未嵌套

output = []
for l in a:
    for e in l:
        if not any([x in e for x in b]):
            output.append(e)

Nested嵌套

output = []
for l in a:
    output.append([x for x in l if not any(z in x for z in b)])

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

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