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

列表元素上的索引输出不正确-Python,python,python-3.6,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] 有人能帮我吗?输出是正确的。迭代值列表,

我刚开始学习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)

输出是正确的。迭代值列表,而不是其索引。条件
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)

你想找到奇数inedx,但你真正要做的是找到奇数元素

for i in lst:  #(i ---->the element in lst)   
    if i % 2 == 1:
所以你应该试试这个

for i in range(len(lst)): #( i ---> the index of lst)
    if i % 2 == 1:

你想找到奇数的inedx,但你真正要做的是找到奇数元素

for i in lst:  #(i ---->the element in lst)   
    if i % 2 == 1:
所以你应该试试这个

for i in range(len(lst)): #( i ---> the index of lst)
    if i % 2 == 1:

根据需要,
奇数索引编号
枚举
提供计数器/索引

def odd_ones_index(lst):
    total = []
    for x,i in enumerate(lst):
        if i % 2 == 1: ## checking i is odd or not
            total.append(x) ## appending index as you want index

    return total
print(odd_ones_index([1,2,3,4,5,6,7,8]))

根据需要,
奇数索引编号
枚举
提供计数器/索引

def odd_ones_index(lst):
    total = []
    for x,i in enumerate(lst):
        if i % 2 == 1: ## checking i is odd or not
            total.append(x) ## appending index as you want index

    return total
print(odd_ones_index([1,2,3,4,5,6,7,8]))

如果您不想将奇数放入数组中,则需要更改条件,因此代码最好如下所示:

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

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

输出:[2,4,6,8]

如果您不想将奇数放入数组中,则需要更改条件,因此代码最好如下所示:

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

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

lst中i的输出:[2,4,6,8]

正在迭代元素,而不是索引。对于枚举(lst)中的i,x,你需要
:如果i%2==1:total.append(x)
对于范围内的i(len(lst))
就足够了。@Taegyung,但你必须索引到
lst
对于范围内的i(len(lst)):#任何带有lst[i]
的东西都是巨大的代码气味。@AdamSmith然后为i编写
,_u
将是不好的做法。等待我想你编辑了<对于枚举(lst)中的i,x,code>看起来已经足够好了。如果这是您首先编写的内容,我很抱歉。您的输出将是[0,2,4,6]而不是[2,4,6,8]
,因为我在lst中
正在迭代元素,而不是索引。对于枚举(lst)中的i,x,你需要
:如果i%2==1:total.append(x)
对于范围内的i(len(lst))
就足够了。@Taegyung,但你必须索引到
lst
对于范围内的i(len(lst)):#任何带有lst[i]
的东西都是巨大的代码气味。@AdamSmith然后为i编写
,_u
将是不好的做法。等待我想你编辑了<对于枚举(lst)中的i,x,code>看起来已经足够好了。如果这是你最初写的,我很抱歉。你的输出将是[0,2,4,6],而不是[2,4,6,8]