3

我想在列表中搜索值 (x) 的出现并返回该值和索引中高于和低于 x 的值的一个数字,比如 2。值 x 可能会多次出现在列表中。

输入

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

输出

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

感谢您的任何帮助或建议

4

3 回答 3

3
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']
于 2013-01-19T11:11:02.357 回答
1

使用的替代解决方案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']
于 2013-01-19T11:11:25.150 回答
1
l = ['a','b','c','d','x','e','f','g','h','i','x','j','k','l']


def search_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']
于 2013-01-19T11:19:40.530 回答