返回列表中项目的所有实例的项目

时间:2014-06-06 02:51:35

标签: python list

说我有一个清单......

['a','brown','cat','runs','another','cat','jumps','up','the','hill']

...我希望浏览该列表并返回特定项目的所有个例以及前往 的2个项目并继续那个项目。如果我正在寻找'猫'

,那就完全一样了
[('a','brown','cat','runs','another'),('runs','another','cat','jumps','up')]

返回的元组列表的顺序是无关紧要的,理想情况是代码句柄实例,其中单词是列表中的第一个或最后一个,当然,高效紧凑的代码片段会更好。

再次感谢大家,我只是在Python中沾沾自喜,这里的每个人都给了我很大的帮助!

3 个答案:

答案 0 :(得分:2)

没有错误检查:

words = ['a','brown','cat','runs','another','cat','jumps','up','the','hill']
the_word = 'cat'

seqs = []

for i, word in enumerate(words):
    if word == the_word:
        seqs.append(tuple(words[i-2:i+3]))

print seqs #Prints: [('a', 'brown', 'cat', 'runs', 'another'), ('runs', 'another', 'cat', 'jumps', 'up')]

答案 1 :(得分:2)

递归解决方案:

def context(ls, s): 
    if not s in ls: return []
    i = ls.index('cat')
    return [ tuple(ls[i-2:i+3]) ] + context(ls[i + 1:], s)

ls = ['a','brown','cat','runs','another','cat','jumps','up','the','hill']

print context(ls, 'cat')

给出:

[('a','brown','cat','runs','another'),('runs','another','cat','jumps','up')]

答案 2 :(得分:2)

进行错误检查:

def grep(in_list, word):
    out_list = []
    for i, val in enumerate(in_list):
        if val == word:
            lower = i-2 if i-2 > 0 else 0
            upper = i+3 if i+3 < len(in_list) else len(in_list)
            out_list.append(tuple(in_list[lower:upper]))
    return out_list

in_list = ['a', 'brown', 'cat', 'runs', 'another', 'cat', 'jumps', 'up', 'the', 'hill']

grep(in_list, "cat")
# output: [('a', 'brown', 'cat', 'runs', 'another'), ('runs', 'another', 'cat', 'jumps', 'up')]

grep(in_list, "the")
# output: [('jumps', 'up', 'the', 'hill')]
相关问题