简体   繁体   English

将项目的索引附加到python中的另一个列表

[英]appending index of an item to another list in python

I used the code below to append the index of an item to another list, but it only gives the index of some previous occurrence of the same item. 我使用下面的代码将一个项目的索引附加到另一个列表,但是它仅给出同一项目的某些先前出现的索引。

for x,y in zip(answer,std_answer):
        if x != y:
           wrong_ans.append(answer.index(x))

Please i need the code to append the exact index of the item to another list. 请我需要将项目的确切索引附加到另一个列表的代码。 Thank you 谢谢

for i, (x, y) in enumerate(zip(answer, std_answer)):
   if x != y
       wrong_ans.append(i)

enumerate is a built-in function that iterates over an iterable, returning the items of the iterable and the iteration index. enumerate是一个内置函数,它在可迭代对象上进行迭代,返回可迭代对象和迭代索引。 It's both faster than index(x) , which searches your list each time it runs, and not subject to identifying earlier appearances of the value. 它都比index(x)快, index(x)每次运行时都在搜索列表,并且无需识别值的更早出现。

Keep it simple: 把事情简单化:

for i in range(min(len(std_answer), len(answer))):
    if answer[i] != std_answer[i]:
        wrong_ans.append(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM