为什么我需要Range(Len))来嵌套if?

时间:2016-07-30 00:31:13

标签: python

这样可行,但当我没有范围(len ..))并且for i in arrfor j in arr时,我在if语句中得到IndexError: list index out of range。这是为什么?

arr = [2,2,2,2,4,5,2,45,3,4,4]

mostFrq = 0
mostFrqAmount = 0

for i in range(len(arr)):

        amountOfCurrent = 0

        # now look at temp element
        for j in range(len(arr)):
                if (arr[j] == arr[i]):
                        amountOfCurrent = amountOfCurrent + 1

        if (amountOfCurrent > mostFrqAmount):
                mostFrqAmount = amountOfCurrent
                mostFrq = arr[i]

print(mostFrq)
print(mostFrqAmount)

3 个答案:

答案 0 :(得分:0)

当您在列表上进行迭代时,您将获得其元素。既然您在该元素的索引处访问了列表元素,那么当它超出界限时它将无法工作(并且无法完成预期的操作)。

相反,只需使用循环提供的项目:

mostFrq = 0
mostFrqAmount = 0

for i in arr:
        amountOfCurrent = 0

        # now look at temp element
        for j in arr:
                if (j == i):
                        amountOfCurrent += 1

        if (amountOfCurrent > mostFrqAmount):
                mostFrqAmount = amountOfCurrent
                mostFrq = i

答案 1 :(得分:0)

不确定您尝试了什么。这应该以相同的方式工作:

arr = [2,2,2,2,4,5,2,45,3,4,4]

mostFrq = 0
mostFrqAmount = 0

for i in arr:

        amountOfCurrent = 0

        # now look at temp element
        for j in arr:
                if (j == i):
                        amountOfCurrent = amountOfCurrent + 1

        if (amountOfCurrent > mostFrqAmount):
                mostFrqAmount = amountOfCurrent
                mostFrq = i

print(mostFrq)
print(mostFrqAmount)

答案 2 :(得分:0)

如果您分析失败表单中代码的内容,您可以:

arr = [2,2,2,2,4,5,2,45,3,4,4]

mostFrq = 0
mostFrqAmount = 0

for i in arr:

        amountOfCurrent = 0

        # now look at temp element
        for j in arr:
                if (arr[j] == arr[i]):
                        amountOfCurrent = amountOfCurrent + 1

        if (amountOfCurrent > mostFrqAmount):
                mostFrqAmount = amountOfCurrent
                mostFrq = arr[i]

print(mostFrq)
print(mostFrqAmount)

使用for i in arr表单返回一个迭代器,为你处理索引信息,所以你的" i"设置为数组中的值。

当你到达这一行时:     if (arr[j] == arr[i]):

您最终使用arr[45]

的变量替换

您的数组索引只会变为10,因此,您会抛出错误。