IndexError: list index out of range in Python 3.5

IndexError: list index out of range in Python 3.5

我正在学习Python3.我有两个列表:

A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]

如果 A 和 B 有任何共同项,则第三个列表应该 return 它们(它们的索引在 B 中)。

[1, 4, 3, 2, 0]

我收到以下错误,

Line 6: IndexError: list index out of range

代码:

class Solution:
    def anagramMappings(self, A, B):
        result =[]
        for i in A:
            for j in B:
                if A[i]==B[i]:
                        result.append(j)
        return result

编辑:感谢您的回答。我想出了以下解决方案。它适用于除此之外的大多数测试用例,

Input:
[40,40]
[40,40]
Output:
[0,0,0,0]
Expected:
[1,1]

代码:

class Solution:
    def anagramMappings(self, A, B):
        result =[]
        for i in A:
            for j in B:
                if i==j:
                        result.append(B.index(j))
        return result

python for 循环遍历元素,而不是索引。因此,首次命中时的 if 语句计算结果为 A[12] == B[50],我认为您不希望在此处出现。请尝试 if i == j

You are iterating over the elements and not the indices of A & B.

行: for i in A 将遍历列表,return 12,28.. 类似的输出也将用于 B 列表。

但是你应该在索引上迭代 ij,所以你通过 len(A)len(B) 得到它们的长度,然后将它转换成一个可迭代的通过使用 python 的 range 函数。 你的代码应该是这样的:

  class Solution:
        def anagramMappings(self, A, B):
            result =[]
            for i in range(len(A)):
                for j in range(len(B)):
                    if A[i]==B[j]:
                            result.append(j)
            return result