python - 列表元素索引的输出不正确 - Python

标签 python python-3.6

刚开始学Python,卡在了这一个。

基本上我想找出奇数索引号中的加号。

这是我的代码。

def odd_ones(lst):
    total = []
    for i in lst:
        if i % 2 == 1:
            total.append(i)
    return total

print(odd_ones([1,2,3,4,5,6,7,8])) 

输出是

[1, 3, 5, 7] 而不是 [2, 4, 6, 8]

有人可以帮我解决这个问题吗?

最佳答案

输出是正确的。您遍历值列表而不是它的索引。条件 i % 2 == 1 给出以下内容:

1 % 2 = 1 (true)
2 % 2 = 0 (false)
3 % 2 = 1 (true)
4 % 2 = 0 (false)
5 % 2 = 1 (true)
6 % 2 = 0 (false)
7 % 2 = 1 (true)
8 % 2 = 0 (false)

所以输出是(1,3,5,7)

关于python - 列表元素索引的输出不正确 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55233240/

相关文章:

python - 为非维护项目的fork创建pypi包

python - 值错误 : Input arrays should have the same number of samples as target arrays. 找到 166 个输入样本和 4 个目标样本

python - 防止 Python webbrowser.open() 控制屏幕并阻止其他进程。可以最小化打开吗?

pycrypto - 在python 3.6中安装pycrypto的问题

python - 无法导入使用 PIP 安装的包

python - 为什么所有对象都使用相同的坐标填充?

python - 提供与 Python 3.6 变量注释的向后兼容性

python - Heroku 和 Django : No default language could be detected for this app

python - 如何使用 Python 和 Zappa 获取 AWS Lambda 剩余时间?

python - 学习算法