1

Having following:

list1 = ['something',"somet'hing",'somet"hing','some;thing','']
list2 = [';','"',"'"]

I would like to get filtered list1 if string inside list contain any of the character from list2 or string is blank. Desired output:

list3 = ['something']

Currently I'm doing it manually like this:

list1withoutEmptyLines= list(filter(None, list1))
list1withoutQuote = [x for x in list1withoutEmptyLines if "'" not in x]
list1withoutDoublequotes = [x for x in list1withoutQuote if "\"" not in x]
list1withoutSemicolon = [x for x in list1withoutDoublequotes if ";" not in x]

and It works perfectly fine. I also tried to automate it through creating list of forbidden characters like this:

forbiddenCharacters = ['"', ';', '\'']
filteredLines = []

for character in forbiddenCharacters:
    filteredLines = [x for x in uniqueLinesInFile if character not in x]

but list called filteredLines still contains strings with semicolon ";". Any advice will be appreciated.

2
  • [x for x in list1 if not any(y in x for y in list2)] Commented Oct 11, 2018 at 16:04
  • You are overwriting filteredLines in each iteration. Commented Oct 11, 2018 at 16:05

1 Answer 1

3

You could do this using a list comprehension combined with the built-in function any:

list1 = ['something', "somet'hing", 'somet"hing', 'some;thing', '']
list2 = [';', '"', "'"]

result = [s for s in list1 if s and not any(c in s for c in list2)]
print(result)

Output

['something']

The list comprehension is equivalent to:

result = []
for s in list1:
    if s and not any(c in s for c in list2):
        result.append(s)
Sign up to request clarification or add additional context in comments.

Comments

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.