# Filter a sequence of strings on keywords

 

def filter_seq(seq, keyw='inp', no_records=2):

    return [(seq[i], seq[i+1:i+1+no_records]) for i in range(len(seq)-no_records) if seq[i]==keyw]

 

seq = ['yuvaraj','sfsfsf','fasdfsf','safsaf','raj','sadfsfsf','safsafsaf','safsdfa',\

       'inp','safsaf','sgsdg','inp','asdfsa','sgsdg','raj','adfsaf','sadfsaf','inp',\

       'wetwt','etwtw','raj','wrqrqr']

 

print filter_seq(seq)

 

 

def filter_seq1(seq, keyw='inp', no_records=2):

    output = []

    for i, item in enumerate(seq):

        if item == keyw:

            output.append((item, seq[i+1:i+1+no_records]))

    return output

 

print filter_seq1(seq)

 

print filter_seq(seq, 'raj', 2)

print filter_seq1(seq, 'raj', 2)

 

# Format output string

print '\n'.join([item for item in [' '.join([s[0], ' '.join(s[1])]) \

                                      for s in filter_seq1(seq, 'inp', 2)]])

 

'''

>>> [('inp', ['safsaf', 'sgsdg']), ('inp', ['asdfsa', 'sgsdg']), ('inp', ['wetwt', 'etwtw'])]

[('inp', ['safsaf', 'sgsdg']), ('inp', ['asdfsa', 'sgsdg']), ('inp', ['wetwt', 'etwtw'])]

[('raj', ['sadfsfsf', 'safsafsaf']), ('raj', ['adfsaf', 'sadfsaf'])]

[('raj', ['sadfsfsf', 'safsafsaf']), ('raj', ['adfsaf', 'sadfsaf']), ('raj', ['wrqrqr'])]

inp safsaf sgsdg

inp asdfsa sgsdg

inp wetwt etwtw

>>>

'''