【问题标题】:Python - get index of list from which on all further entries satisfy conditionPython - 获取所有进一步条目满足条件的列表索引
【发布时间】:2021-06-26 14:12:54
【问题描述】:

假设我有一个列表

l = [12,13,14,10,13,14]

我想找到所有项目上大于10 的索引(在这种情况下,索引4 对应于13 作为此属性的第一次出现)。

可能基于this,如何用Python做到最好?

我的想法:为此创建一个布尔列表 [a>10 for a in l](由 TrueFalse 作为序列组成),或者 l>10 以某种方式使用 numpy 产生一个数组?

【问题讨论】:

  • 你想要所有大于10的数字的索引吗?
  • 你想要的输出是什么?

标签: python arrays numpy boolean


【解决方案1】:

给你:

[l.index(item) for item in l if not item>10][-1]+1

【讨论】:

    【解决方案2】:

    您可以向后遍历列表并捕获第一个条件失败的索引。这可以防止出现多个值失败的问题...

    In [51]: l                                                                                  
    Out[51]: [12, 13, 14, 10, 13, 14]
    
    In [52]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
    Out[52]: 4
    
    In [53]: l = [12, 13, 10, 20, 10, 15]                                                       
    
    In [54]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
    Out[54]: 5
    
    In [55]: l = [23, 55]                                                                       
    
    In [56]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
    
    In [57]: 
    
     
    

    【讨论】:

      【解决方案3】:
      l = [12,13,14,10,13,14]
      i = len(l)
      for i in reversed(l):
          condition = v > 10
          if not condition:
              break
          i -= 1
      print(i)
      # Output : 4
      

      注意列表的最后一个元素不满足条件的情况。 i 值将等于 len(l) ,这不是列表的有效索引。由您决定如何管理这种特殊情况。

      【讨论】:

        【解决方案4】:

        你可以从数组的末尾开始:

        def findStartOfMoreThan(l,limit):
            for i in range(len(l)-1, -1, -1):
                if l[i]<=limit :
                    return i+1
            return (-1)
            
        assert(findStartOfMoreThan([12,13,14,10,13,14],10) == 4)
        assert(findStartOfMoreThan([12,13,14,10,13,14,15],10)==4)
        assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],10)==5)
        assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],13)==6)
        

        【讨论】:

          【解决方案5】:

          最简单的解决方案是否定条件以获取具有element &lt;=10 的最后一个索引使用

          l = np.array([12,13,14,10,13,14])
          first_index = np.where(l<=10)[0][-1]+1 # yields the first index that satisfies the condition
          

          可以首先检查len(np.where(...)) 以验证条件是否被违反至少一次,否则为第一个索引返回 0。

          【讨论】:

            猜你喜欢
            • 2011-11-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-06-09
            相关资源
            最近更新 更多