英文:
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?
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?
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论