0

I need to remove the sub lists from a list in Python.

For example: The main list A contains

A=[ 'a,b,c', 'd,e,f' , 'g,h,i' , 'g,l,m' , 's,l,k' , 'd,k,l', 'a,g,d' ]

I need to remove the sub lists from A which begin with the items in the following list:

B = ['g','d']

so that Final List A = [ 'a,b,c', 's,l,k' , 'a,g,d' ]

Thanks in advance

P_Ar
  • 377
  • 2
  • 9
  • 25
  • 1
    That is not a sub list but an element of a flat list – DirtyBit Jun 17 '20 at 00:18
  • Why isn't `'d,e,f'` removed? – wjandrea Jun 17 '20 at 00:22
  • Does this answer your question? [Filtering a list of strings based on contents](https://stackoverflow.com/questions/2152898/filtering-a-list-of-strings-based-on-contents), [Checking whether a string starts with XXXX](https://stackoverflow.com/q/8802860/4518341) – wjandrea Jun 17 '20 at 00:24
  • 1
    Even your output seems wrong. It should be `['a,b,c', 's,l,k', 'a,g,d']`. 2nd Element `'d,e,f'` should also be removed as start element `'d'` is in second list. – Astik Anand Jun 17 '20 at 00:27
  • also [str.startswith with a list of strings to test for](https://stackoverflow.com/q/20461847/4518341) – wjandrea Jun 17 '20 at 00:38
  • Question updated.. @wjandrea Thanks for pointing out. – P_Ar Jun 17 '20 at 01:03

2 Answers2

2

Using list comprehension:

print([x for x in A if x[0] not in ['g', 'd']])
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

You can do it using list comprehension and split(",").

print([e for e in A if e.split(",")[0] not in B])

Output

['a,b,c', 's,l,k', 'a,g,d']

Your output above for your approach is wrong. 2nd Element 'd,e,f' should also be removed as start element 'd' is in second list.

Astik Anand
  • 12,757
  • 9
  • 41
  • 51