0

I have list of values , need to filter out values , that doesn't follow a naming convention.

like below list : list = ['a1-23','b1-24','c1-25','c1-x-25']
need to filter : all values that starts with 'c1-' , except 'c1-x-' )

output expected: ['a1-23','b1-24','c1-x-25']

list = ['a1-23','b1-24','c1-25','c1-x-25']
[x for x in list if not x.startswith('c1-')]
['a1-23', 'b1-24']
1
  • 1
    Please try to avoid using list as a variable name Commented Nov 29, 2020 at 22:53

2 Answers 2

1

You have the right idea, but you're missing the handing of values that start with c1-x-:

[x for x in list if not x.startswith('c1-') or x.startswith('c1-x-')]
Sign up to request clarification or add additional context in comments.

1 Comment

Just adding my solution here in comments because its similar - [i for i in l if 'c1' not in i.split('-') or 'x' in i.split('-')]
1
import re

list1 = ['a1-23','b1-24','c1-25','c1-x-25',"c1-22"]
r = re.compile(r"\bc1-\b\d{2}$") # this regex matches anything with `c1-{2 digits}` exactly
[x for x in list1 if x not in list(filter(r.match,list1))]

# output
['a1-23', 'b1-24', 'c1-x-25']

So what my pattern does is match EXACTLY a word that starts with c1- and ends with two digits only.

Therefore, list(filter(r.match,list1)) will give us all the c1-## and then we do a list comprehension to filter out from list1 all the x's that aren't in the new provided list containing the matches.

x for x in [1,2,3] if x not in [1,2]
#output
[3]

2 Comments

Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
@wscourge will do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.