【问题标题】:Search a list for item(s)and return x number of surrounding items in python在列表中搜索项目并在 python 中返回 x 个周围项目
【发布时间】:2013-01-03 00:49:56
【问题描述】:

我想在列表中搜索某个值 (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']

感谢您的帮助或建议

【问题讨论】:

    标签: python list indexing slice


    【解决方案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 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']
    

    【讨论】:

    • +1:我的解释是错误的。还要考虑边界条件(列表两端的“x”)。
    • 你可以在for循环中做out.extend(lis[i-2:i+3])
    • @Abhijit 我不确定在这些情况下的预期输出是什么。
    • 谢谢大家。 @AshwiniChaudhary 边界条件将包括 x 如果在边界处找到。您的解决方案非常有帮助。
    【解决方案2】:
    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']
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • @AshwiniChaudhary:将我的解决方案更改为使用 difflib.SequenceMatcher
      • @AshwiniChaudhary:您的解决方案更快,但是当 needle 是多字符串时,应该选择这个。
      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2011-05-26
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多