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

问题描述 投票:1回答:4

我刚刚开始研究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 python-3.6
4个回答
1
投票

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


1
投票

你想找到奇数索引,但你真正做的是找到奇数元素

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:

1
投票

如果您不想将奇数输入阵列,则需要更改条件,因此代码最像是这样的:

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]


1
投票

根据要求odd index numberenumerate提供了反/指数

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]))
© www.soinside.com 2019 - 2024. All rights reserved.