这是可行的,但是当我没有范围(len ..))并且做了for i in arr
和for j in arr
,我在if语句上得到了IndexError: list index out of range
。为什么是这样?为什么我需要范围(Len))嵌套的if?
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)
因为其中一项是'45'。由于列表中没有足够的数字,这会引发错误。 – zondo
顺便说一句,你应该考虑使用['collections.Counter(arr).most_common(1)'](https://docs.python.org/3/library/collections.html#collections.Counter.most_common)。 –