Reputation: 2014
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']]
Upvotes: 1
Views: 382
Reputation: 239653
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']]
Upvotes: 1