python - 我的偶数 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]
解决方案
我想与您分享的是,您不必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]
推荐阅读
- python - 我们如何编写一个函数来获取重复值的行号并获取最小值(行号)?
- python-3.x - ndarray.tranpose(2,0,1) 产生意外结果
- android - executePendingTransactions 冲突
- python - 如何在客户端的对象中获取数组?
- python - Jupyter 扩展安装失败,因为 NPM 包无效
- c++ - 如何正确比较整数和浮点值?
- javascript - 无法从 console.log(document.documentElement.scrollLeft) 获得滚动的像素数。在 Chrome 中返回总是 0
- java - 如何使用强制转换运算符
- angular - 为什么这段代码会出现类型转换错误?
- reactjs - 在 Gatsby 中使用类组件时出现错误