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 m
Solution 1:
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 inind:
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]: fromitertoolsimport *
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']
Solution 2:
l = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']
defsearch_w(mylist,item,before=1,after=1):
newl=[]
l = mylist[:]
while item in l:
i = l.index(item)
newl+= l[i-before:i+after+1]
l = l[i+after:]
return newl
>>> print search_w(l,'x',2,2)
['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']
Solution 3:
An alternate solution using difflib.SequenceMatcher
>>> from itertools import chain
>>> from difflib import SequenceMatcher
>>> in_data = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']
>>> sm = SequenceMatcher(None, in_data, 'x'*len(in_data)).get_matching_blocks()
>>> list(chain(*(in_data[m.a -2 : m.a + 3] for m in sm[:-1])))
['c', 'd', 'x', 'e', 'f', 'h', 'i', 'x', 'j', 'k']
Post a Comment for "Search A List For Item(s)and Return X Number Of Surrounding Items In Python"