【问题标题】:finding index[] of odd values in a list of integers?在整数列表中查找奇数的索引[]?
【发布时间】:2023-01-12 20:35:11
【问题描述】:

我试图在列表中找到一些奇数整数的索引值。该程序在当前阶段仅返回一个仅包含奇数的新列表。

image of my code

该程序返回值 [3, 5, 7]。我如何才能检索这些奇数的索引呢?例如,[0, 1, 3, 5] 用于上面显示的列表。

我试过“position = dataItem1.index()”。我知道我需要在索引括号内输入一个索引值。

【问题讨论】:

  • 将代码发布为文本,而不是图像。

标签: python list indexing


【解决方案1】:

不要在奇数列表中的那个索引上添加元素,只需添加索引

像这样odds.append(index)

【讨论】:

    【解决方案2】:

    您已经知道索引,它是循环变量

    def positionOfOdds(arr):
        odds = []
        length = len(arr)
        
        index = 0
        while index < length:
            data = arr[index]
            if data % 2 != 0:
                odds = odds + [index]
            index += 1
        return odds
    

    【讨论】:

      【解决方案3】:

      您也可以使用 enumerate :它返回元素和元素的索引(另外,在 python 中,您可以直接遍历列表的元素,不需要 while 循环)。我还鼓励使用 .append() 将元素添加到列表中,这显然比连接两个列表更有效:

      l = [0, 3, 2, 3, 4, 7, 6]
      
      def get_odds_index(l):
          res = []
          for idx, val in enumerate(l):
              if val % 2 != 0:
                  res.append(idx)
          return res
      
      get_odds_index(l)
      

      【讨论】:

        【解决方案4】:

        您使用一个名为 odds 的数组来存储奇数,以获取您可以创建的索引,而不是一个数组来存储奇数的索引,我将其称为 odds_idxs。它应该看起来像这样:

        num_list = [0, 3, 2, 3, 4, 7, 6]
        def position_of_odds(num_list):
          odds_idxs = []
          length = len(num_list)
          index = 0
          while index < length:
            if num_list[index] % 2 != 0:
              odds_idxs = odds_idxs + [index]
            index = index + 1 
          return odds_idxs
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-01
          • 2023-03-15
          • 2018-07-21
          • 1970-01-01
          • 2017-05-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多