首页 > 解决方案 > 我的偶数 python 函数索引只返回列表中的第一个偶数。如何让它返回列表中所有偶数的索引?

问题描述

我正在尝试编写一个 python 函数来返回列表中所有偶数的索引。但是,它只返回第一个偶数的索引。

我的代码

def indicesOfEvens(listOfInt):
"""return list with indices (indexes) of each even int
if no even ints in the list, return an empty list
if listOfInt isn't a list, or has something that isn't an int,
raise ValueError
"""
  if (type(listOfInt) != list):
    raise ValueError("must be list")
  for item in listOfInt:
    if (type(item) != int):
      raise ValueError("must be list of ints")
  index= []
  for i in range(0,len(listOfInt)):
    if listOfInt[i] % 2 == 0:
      return index + listOfInt[i]
  return index

测试用例

def test_indicesOfEvens_1():
  assert indicesOfEvens([11,20,35,44,57,63,42])==[1,3,6]

标签: python

解决方案


我想与您分享的是,您不必return在这部分代码中执行 a ,但您必须使用+=or append。所以而不是:

     return index + listOfInt[i]

… 做就是了:

    index.append(listOfInt[i])

所以解决方案是:

def indicesOfEvens(listOfInt):
    """return list with indices (indexes) of each even int
    if no even ints in the list, return an empty list
    if listOfInt isn't a list, or has something that isn't an int,
    raise ValueError
    """
    if (type(listOfInt) != list):
        raise ValueError("must be list")
    for item in listOfInt:
        if (type(item) != int):
            raise ValueError("must be list of ints")
    index= []
    for i in range(0,len(listOfInt)):
        if listOfInt[i] % 2 == 0:
            index.append(listOfInt[i])
    return index

def test_indicesOfEvens_1(): 
     assert indicesOfEvens([11,20,35,44,57,63,42])==[1,3,6]

推荐阅读