我有一个句子列表。例如:
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”的选项。 我怎么能在 python 3 上做到这一点? 我试过这个:
l = []
for i in x:
for k in i:
if i.index(k) != (len(i) -2):
l.append(' '.join(i))
我在小列表上工作,但不在大列表上工作(几千个元素)
最佳答案
您可以使用带有 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']
关于python - 从字符串列表中选择合适的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485448/