【问题标题】:Find the indices of first positive elements in list - python查找列表中第一个正元素的索引 - python
【发布时间】:2019-10-10 19:56:30
【问题描述】:

我正在尝试查找每个正值序列的起始位置的索引。我只得到了代码中正值的位置。我的代码如下所示:

index = []
for i, x in enumerate(lst):
  if x > 0:
    index.append(i)
print index

我希望 [-1.1, 2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9] 的输出为 [1, 8]

【问题讨论】:

    标签: python python-2.7 list indexing


    【解决方案1】:

    我认为如果你使用列表理解会更好

    index = [i for i, x in enumerate(lst) if x > 0]
    

    【讨论】:

      【解决方案2】:

      目前您正在选择数字为正数的所有索引,而不是仅当数字从负数变为正数时才收集索引。

      此外,您还可以处理所有负数,或从正数开始的数字

      def get_pos_indexes(lst):
      
          index = []
      
          #Iterate over the list using indexes
          for i in range(len(lst)-1):
      
              #If first element was positive, add 0 as index
              if i == 0:
                  if lst[i] > 0:
                      index.append(0)
              #If successive values are negative and positive, i.e indexes switch over, collect the positive index
              if lst[i] < 0 and lst[i+1] > 0:
                  index.append(i+1)
      
          #If index list was empty, all negative characters were encountered, hence add -1 to index
          if len(index) == 0:
              index = [-1]
      
          return index
      
      print(get_pos_indexes([-1.1, 2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
      print(get_pos_indexes([2.0, 3.0, 4.0, 5.0, -2.0, -3.0, -4.0, 5.5, 6.6, 7.7, 8.8, 9.9]))
      print(get_pos_indexes([2.0,1.0,4.0,5.0]))
      print(get_pos_indexes([-2.0,-1.0,-4.0,-5.0]))
      

      输出将是

      [1, 8]
      [0, 7]
      [0]
      [-1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-25
        • 2015-12-16
        • 2019-11-11
        • 2021-08-23
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        • 2017-11-11
        相关资源
        最近更新 更多