Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a list for item(s)and return x number of surrounding items in python

I want to search a list for the occurence of a value (x) and return that value and a number, say 2, of the values above and below x in the index. Value x might appear in the list multiple time.

Input

in = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']

Output

out = ['c','d','x','e','f','h','i','x','j','k']

Thanks for any help or suggestions

like image 972
bradj Avatar asked Dec 14 '25 06:12

bradj


1 Answers

In [8]: lis = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']

#create a new list containing all the index positions of 'x'

In [9]: ind=[i for i,x in enumerate(lis) if x=='x']

In [10]: out=[]

# loop over ind list, and for every index i:
# here lis[i-2:i] are the elements left to the 'x' and similarly lis[i:i+3]
# are the ones to its right.
# which is  simply  lis[i-2:i+3] as suggested by @volatility

In [11]: for i in ind:
    out.extend(lis[i-2:i+3])

   ....:     


In [12]: out
Out[12]: ['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']

A one-liner using itertools.chain():

In [19]: from itertools import *

In [20]: list(chain(*[lis[i-2:i+3] for i in ind]))
Out[20]: ['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']
like image 189
Ashwini Chaudhary Avatar answered Dec 16 '25 20:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!