两个列表对应元素相同的索引列表
我想比较两个不同的列表并返回类似刺痛的索引。
例如,如果我有两个列表,例如:
grades = ['A', 'B', 'A', 'E', 'D']
scored = ['A', 'B', 'F', 'F', 'D']
我的预期输出是:
[0, 1, 4] #The indexes of similar strings in both lists
然而,这是我目前得到的结果:
[0, 1, 2, 4] #Problem: The 2nd index being counted again
我尝试使用两种方法进行编码。
第一种方法:
def markGrades(grades, scored):
indices = [i for i, item in enumerate(grades) if item in scored]
return indices
第二种方法:
def markGrades(grades, scored):
indices = []
for i, item in enumerate(grades):
if i in scored and i not in indices:
indices.append(i)
return indices
第二种方法返回正确的字符串,但不返回索引。
回答
您可以在列表理解中使用enumeratewith来实现这一点:zip
>>> grades = ['A', 'B', 'A', 'E', 'D']
>>> scored = ['A', 'B', 'F', 'F', 'D']
>>> [i for i, (g, s) in enumerate(zip(grades, scored)) if g==s]
[0, 1, 4]
您的代码问题在于您没有比较同一索引处的元素。相反,通过使用in您正在检查一个列表的元素是否存在于另一个列表中。
由于'A'指数2的grades出现在scored列表中。您正在2结果列表中获取索引。