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

标签 python python-3.x loops select

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

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/

相关文章:

javascript - `_.forEach`和 `$.each`的区别

python - 如何使用 openpyxl 循环遍历 Excel 工作表的行?

python - Tkinter,调用带参数的函数

python - 具有不同表达式的 Lambda 返回相同的输出

python-3.x - 在 TensorFlow 中使用多个 GPU 来推断 pb 模型

java - 使用Bash脚本通过java代码运行多个文件

python - Tkinter 和多线程

python - 基于列 Pandas 值的不同聚合函数

python - 使用streamlit Python代码找不到上传文件的路径

python - 使用元图 tensorflow 运行模型失败