【发布时间】:2021-04-29 20:59:05
【问题描述】:
我想比较两个不同的列表并返回相似字符串的索引。
例如,如果我有两个类似的列表:
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
第二种方法返回正确的字符串,但不返回索引。
【问题讨论】:
-
请注意,
if item in scored如果该成绩有任何匹配项,则通过。它不查看匹配的索引。
标签: python python-3.x string list enumerate