为什么我的for循环与if语句一起不起作用?

huangapple go评论74阅读模式
英文:

Why does my for loop not work with an if statement

问题

I want the function to return a list of the indices where the values were equal in lst1 and lst2. When I run my code it only returns [0]. Does anyone know what I'm doing wrong?

为什么我的for循环与if语句一起不起作用?

It should've returned [0, 2, 3]. I also tried adding an Else: continue, but that didn't help.

英文:

I want the function to return a list of the indices where the values were equal in lst1 and lst2. When I run my code it only returns [0]. Does anyone know what I'm doing wrong?

为什么我的for循环与if语句一起不起作用?

It should've returned [0, 2, 3]. I also tried adding an Else: continue, but that didn't help.

答案1

得分: 0

你得到 [0] 是因为你的计数器 x 应该在 if 条件之外。

def same_values(lst1, lst2):
    new = []
    x = 0
    for num in lst1:
        if num == lst2[x]:
            new.append(x)
        x = x + 1
    return new

或者,你也可以通过以下方式获取索引:

list1 = [5, 1, -10, 3, 3]
list2 = [5, 10, -10, 3, 5]

[index for index, value in enumerate(list1) if list2[index] == value]

# 输出
[0, 2, 3]
英文:

You are getting [0] because your counter x should be outside if condition.

def same_values(lst1,lst2):
    new=[]
    x=0
    for num in lst1:
        if num==lst2[x]:
            new.append(x)
        x=x+1
       
    return new

Alternatively, you can also get the indices by:

list1=[5,1,-10,3,3]
list2=[5,10,-10,3,5]

[index for index,value in enumerate(list1) if list2[index] == value]

#output
[0, 2, 3]

huangapple
  • 本文由 发表于 2023年5月18日 09:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定