1

I am trying to remove sublist from nested lists based on elements values.

data = [['1', 'i like you'],
['2', 'you are bad'],
['5', 'she is good'],
['7', 'he is poor']]

negative_words = set(['poor', 'bad'])

If the second column contains negative words, I would like to remove the sub-lists. So, the desired results are below. Any suggestions?

data = [['1', 'i like you'],
['5', 'she is good']]

1 Answer 1

1

I can readily think of two ways.

>>> data = [['1', 'i like you'], ['2', 'you are bad'],
            ['5', 'she is good'], ['7', 'he is poor']]
>>> neg_words = {'poor', 'bad'}

Use convert string in the sublist to a set, and then check if it is disjoint with neg_words, like this

>>> [[n, ws] for n, ws in data if set(ws.split()).isdisjoint(neg_words)]
[['1', 'i like you'], ['5', 'she is good']]

Or simply check if none of words from the string in the list, is in neg_words, like this

>>> [[n, ws] for n, ws in data if all(w not in neg_words for w in ws.split())]
[['1', 'i like you'], ['5', 'she is good']]
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.