【问题标题】:How to find the index of the nth time an item appears in a list?如何找到一个项目第n次出现在列表中的索引?
【发布时间】:2014-04-11 14:42:17
【问题描述】:

给定:

x = ['w', 'e', 's', 's', 's', 'z','z', 's']

s 的每次出现都出现在以下索引处:

第一:2
第二:3
第三:4
第四名:7

如果我这样做x.index('s'),我将获得第一个索引。

如何获取第四个s的索引?

【问题讨论】:

标签: python list indexing iterable


【解决方案1】:

使用list comprehensionenumerate

>>> x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
>>> [i for i, n in enumerate(x) if n == 's'][0]
2
>>> [i for i, n in enumerate(x) if n == 's'][1]
3
>>> [i for i, n in enumerate(x) if n == 's'][2]
4
>>> [i for i, n in enumerate(x) if n == 's'][3]
7

【讨论】:

    【解决方案2】:

    如果您不想存储每次出现的索引,或者想使用任意可迭代对象,那么类似:

    from itertools import islice
    
    def nth_index(iterable, value, n):
        matches = (idx for idx, val in enumerate(iterable) if val == value)
        return next(islice(matches, n-1, n), None)
    
    x = [ 'w', 'e', 's', 's', 's', 'z','z', 's']
    idx = nth_index(x, 's', 4)
    # 7
    

    注意next 中有一个默认值None。您可能希望将其更改为其他内容,或将其删除并捕获 StopIteration 并作为另一个更合适的异常引发(例如 ValueError,以便它与 list.index 行为更多地联系在一起)。

    【讨论】:

      【解决方案3】:

      获取项目的索引:

      return [index for index, char in enumerate(x) if char == 's']
      

      获取角色本身:

      return [char for index, char in enumerate(x) if char == 's']
      

      或者获取字符/索引对的元组: (感谢 falsetru 指出更简单的解决方案)

      pairs = [(index, char) for index, char in enumerate(x) if char == 's']
      

      【讨论】:

      • enumerate 产生index-element 对,而不是element-index 对。而[char, index for ...] 会导致 SytnaxError。
      • 糟糕,让我来解决这个问题
      • 最后一个代码可以替换为pairs = [(index, char) for index, char in enumerate(x) if char == 's']pairs = [pair for pair in enumerate(x) if pair[1] == 's']
      【解决方案4】:
      def find_nth_character(str1, substr, n):
          """find the index of the nth substr in string str1""" 
          k = 0
          for index, c in enumerate(str1):
              #print index, c, n  # test
              if c == substr:
                  k += 1
                  if k == n:
                      return index
      
      
      str1 = "B.765.A87_43.Left.9878.xx8"
      substr = '.'
      occurance = 4
      
      print "%s #%d at index %d" % (substr, occurance, find_nth_character(str1, substr, occurance))
      

      【讨论】:

        【解决方案5】:

        这是一种使用 itertools.count 和生成器表达式的更 Pythonic 的方法:

        In [24]: def get_nth_index(lst, item, n):
            ...:     c = count()
            ...:     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)
        

        演示:

        In [25]: get_nth_index(x, 's', 2)
        Out[25]: 3
        
        In [26]: get_nth_index(x, 's', 3)
        Out[26]: 4
        
        In [27]: get_nth_index(x, 's', 4)
        Out[27]: 7
        
        In [28]: get_nth_index(x, 's', 5)
        ---------------------------------------------------------------------------
        StopIteration                             Traceback (most recent call last)
        <ipython-input-28-fc4e5e8c31ef> in <module>()
        ----> 1 get_nth_index(x, 's', 5)
        
        <ipython-input-24-5394f79b3c30> in get_nth_index(lst, item, n)
              1 def get_nth_index(lst, item, n):
              2     c = count()
        ----> 3     return next(i for i, j in enumerate(x) if j=='s' and next(c) == n-1)
        
        StopIteration: 
        
        In [29]: 
        

        如您所见,如果找不到匹配项,它将引发StopIteration 异常。您还可以将默认参数传递给next() 函数以返回默认值而不是引发异常。

        【讨论】:

          【解决方案6】:

          我们可以简单地扩展内置列表类的功能。通过继承它。

          In [64]: class List(list):
                 :     def __init__(self, *val):
                 :         self.extend(list(val))
                 :
                 :
                 :     def findidx(self, val, n=None):
                 :         '''return the occurances of an object in a list'''
                 :
                 :         if n == None:
                 :             return [i for i, v in enumerate(self) if v == val]
                 :
                 :         return [i for i, v in enumerate(self) if v == val][n]
          

          并且有两种方法可以使用这个类。请参阅以下示例以了解。

          In [65]: c = List(4, 5, 6, 7, 2, 5, 4 ,4) # enter the elements of the list as a argument
          
          In [69]: c.findidx(4, 0) # search 4's 0th(1) occurance
          Out[69]: 0
          
          In [72]: c.findidx(4, 1) # find 4's 1st(2) occurance
          Out[72]: 6
          

          In [66]: c.findidx(4) # find all occurances of 4
          Out[66]: [0, 6, 7]
          
          In [67]: c.findidx(4)[0] # first occurance
          Out[67]: 0
          
          In [67]: c.findidx(4)[2] # third occurance
          Out[67]: 7
          
          In [69]: c[0]# for verification
          Out[69]: 4
          
          In [70]: c[7]
          Out[70]: 4
          

          `

          【讨论】:

            【解决方案7】:

            您可以使用它来查找最后一个位置

            其中 a 是数组

            t=(a.index(0)+a.count(0))-1

            您可以将数字增加到 -2 或 -3 以查找所需数字的位置

            注意:列表必须排序。可以用sort()进行排序

            例如: a.sort()

            for more inbuilt function in list click here

            【讨论】:

              猜你喜欢
              • 2012-01-10
              • 2020-03-16
              • 1970-01-01
              • 2023-03-12
              • 1970-01-01
              • 2020-03-12
              • 2017-05-06
              • 2021-04-14
              • 2021-07-29
              相关资源
              最近更新 更多