IndexError:列表索引超出范围 - 对于ar在arr1和arr2中的i

时间:2016-11-02 07:39:52

标签: python

您将看到两个数组,所有数组都包含正整数。其中一个数组将有一个额外的数字,见下文:

[1,2,3][1,2,3,4]应该返回4

[4,66,7][66,77,7,4]应该返回77

我的代码:

def find_missing(arr1, arr2):  
  if len(arr1) != len(arr2):  
    for i in arr1 and arr2:  
        if arr1[i] != arr2[i]:  
          return i

产生此错误:

Traceback (most recent call last): File "python", line 1, 
in <module> File "python", line 4, in find_missing 
IndexError: list index out of range

3 个答案:

答案 0 :(得分:1)

您的代码似乎没有执行您的意思 - 这是另一个问题。

错误在这里:

for i in arr1 and arr2:
    if arr1[i] != arr2[i]:  
arr1中的

i 不是 an index,而是直接its element。 (Length数组可能为4,但其中的元素可能为66。)

解决方案可能就像这样简单:

def find_missing(arr1, arr2):
    diff = [i for i in arr1 if i not in arr2] + [i for i in arr2 if i not in arr1]
    return diff[0] if len(diff) > 0  else None

答案 1 :(得分:1)

这可能是这样做的一种方式:

def find_missing(arr1, arr2):

    # Set longer array to lst1, shorter to lst2 
    if len(arr1) > len(arr2):
        lst1 = arr1
        lst2 = arr2
    else:
        lst1 = arr2
        lst2 = arr1

    # Go through elements in longer list
    for element in lst1:

        # If this element is not in lst2, we found it, return result
        if element not in lst2:
            return element

答案 2 :(得分:0)

def find_missing(list1, list2):
    try:        
        if len(list1) > len(list2):
            return [element for element in list1 if element not in list2][0]
        else:
            return [element for element in list2 if element not in list1][0]
    except IndexError:
        return None