selecting suitable options from list of strings

Viewed 75

I have a list of sentences. For example:

x = ['Mary had a little lamb', 
           'Jack went up the hill', 
           'Jill followed suit',    
           'i woke up suddenly',
           'I just missed the train',
           'it was a really bad dream']

I want to select those options in which the penultimate word is not 'the'. How could i do it on python 3? I tried this:

l = []
for i in x:
    for k in i: 
        if i.index(k) != (len(i) -2):
             l.append(' '.join(i))

I works on a small lists but not on huge ones(several thousands elements)

4 Answers

You can use a list comprehension with split to separate the sentence into words, then use index [-2] to check the penultimate element.

>>> [s for s in x if s.split()[-2] != "the"]
['Mary had a little lamb',
 'Jill followed suit',
 'i woke up suddenly',
 'it was a really bad dream']
x = ['Mary had a little lamb', 
           'Jack went up the hill', 
           'Jill followed suit',    
           'i woke up suddenly',
           'I just missed the train',
           'it was a really bad dream']

result = [y for y in x if y.split()[-2].lower() != 'the']

print(result)
# ['Jack went up the hill', 'I just missed the train']

You could use the filter() method and pass through a lambda which will return true for strings which don't have "the" as the second last word:

x = ['Mary had a little lamb', 
           'Jack went up the hill', 
           'Jill followed suit',    
           'i woke up suddenly',
           'I just missed the train',
           'it was a really bad dream']

res = list(filter(lambda str : str.split()[-2] != "the", x)) 
print(res) # ['Mary had a little lamb', 'Jill followed suit', 'i woke up suddenly', 'it was a really bad dream']
x = ['Mary had a little lamb', 
           'Jack went up the hill', 
           'Jill followed suit',    
           'i woke up suddenly',
           'I just missed the train',
           'it was a really bad dream']

res =[sentence for sentence in x if 'the'!= sentence.split()[-2]]

print(res)

output

['Mary had a little lamb', 'Jill followed suit', 'i woke up suddenly', 'it was a really bad dream']
Related