【问题标题】:List of index where corresponding elements of two lists are same两个列表的对应元素相同的索引列表
【发布时间】: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


【解决方案1】:

您可以在列表理解中使用enumeratezip 来实现:

>>> 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,您正在检查一个列表的元素是否存在于另一个列表中。

因为grades 的索引2 处的'A' 存在于scored 列表中。您将在结果列表中获得索引 2

【讨论】:

  • 感谢您以清晰的解释帮助我理解。非常感谢。
【解决方案2】:

你的逻辑失败了,它不检查元素是否在相同的位置,只是grades 元素出现在scored 中的某处。如果只是简单地检查对应的元素,就可以简单地做到这一点。

使用第二种方法:

for i, item in enumerate(grades):
    if item == scored[i]:
        indices.append(i)

Anonymous 给出的解决方案是我即将添加的解决问题的“Pythonic”方式。

【讨论】:

  • 感谢您也更正了第二种方法,帮助我理清了概念。
【解决方案3】:

您可以使用zip 成对访问这两个列表(以避免过度概括地在另一个数组中的任何位置找到匹配项)

grades = ['A', 'B', 'A', 'E', 'D']
scored = ['A', 'B', 'F', 'F', 'D']

matches = []
for ix, (gr, sc) in enumerate(zip(grades,scored)):
    if gr == sc:
        matches.append(ix)

或者更紧凑的列表理解,如果这适合你的目的

matches = [ix for ix, (gr, sc) in enumerate(zip(grades,scored)) if gr == sc]

【讨论】:

  • 谢谢,这有帮助。
猜你喜欢
  • 2018-08-09
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 2018-05-02
  • 2020-03-08
  • 1970-01-01
相关资源
最近更新 更多