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']
使用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']