从字符串列表中选择合适的选项

2024-05-21 06:04:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个句子列表。例如:

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']

我想选择倒数第二个单词不是“the”的选项。 如何在python3上实现它? 我试过这个:

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

我在一个小的列表上工作,但不在大的列表上工作(几千个元素)


Tags: thein列表for句子jackupmary
3条回答

您可以使用列表理解和split将句子分隔成单词,然后使用索引[-2]检查倒数第二个元素。你知道吗

>>> [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']

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

print(res)

输出

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

您可以使用filter()方法并传递lambda,对于没有"the"作为最后一个单词的字符串,该lambda将返回true:

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']

相关问题 更多 >