获取包含列表[i + 1]的子列表,其中list [i]是特定值

时间:2014-07-06 21:49:05

标签: parsing python-3.x

这句话很难说。

说我有名单

['There,', 'calls', 'the', 'mariner', 'there', 'comes', 'a', 'ship', 'over',
'the', 'line', 'But', 'how', 'can', 'she', 'sail', 'with', 'no', 'wind', 'in',
'her', 'sails', 'and', 'no', 'tide.', 'See...', 'onward', 'she', 'comes', 'Onwards',
'she', 'nears,', 'out', 'of', 'the', 'sun', 'See...', 'she', 'has', 'no', 'crew',]

如何从中提取列表

['sail', 'comes', 'nears', 'has']

那就是,“她”之后立即出现的每一个元素?可以用列表理解来完成吗?

2 个答案:

答案 0 :(得分:2)

适用于所有情况:

[li[i+1] for i in range(len(li)-1) if li[i]=='she']

li为您的列表...

对于较大的列表,您可以使用itertools中的pairwise recipe或者:

def pairs(li):
    # Python 2 -- use izip instead of zip
    from itertools import islice
    for this_item, next_item in zip(li, islice(li, 1, None)):
        yield this_item, next_item

然后你的结果是:

list(that for this, that in pairs(li) if this=='she')

其优点是不构建中间列表。

答案 1 :(得分:1)

由于此列表中存在一些边缘情况,例如

[word for i, word in enumerate(lst[1:], 1) if lst[i-1]=="she"]
# misses the first match if lst[0] == 'she'

[lst[i+1] for i,word in enumerate(lst) if word=='she']
# IndexError if lst[-1] == 'she'

我建议改用正则表达式。

import re
words_string = ' '.join(lst)
pat = re.compile(r"""
         \bshe\s      # literal 'she '
         (\w+)\b      # match next word up to the word break""",
                 flags=re.X)
target = pat.findall(words_string)
相关问题