gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:52:13 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com