这是我的错误:
Traceback (most recent call last):
File "N:\Downloads\#swig.py", line 45, in <module>
print("Mode =", numdict2[1])
IndexError: list index out of range
这是我的密码:
lennumlist = int(1)
x = 1
y = 0
newlist = []
added = 0
numlist = []
while x < 6:
print("This is number",x)
num1 = int(input("Number?"))
x = x + 1
numlist.append(num1)
print("Your numbers =", numlist)
print("Calculating mean...")
while y < 5:
num = numlist[y]
added = added + num
y = y + 1
divide = added / len(numlist)
print("Your mean is", divide)
print("Calculating mode...")
numlist.sort
numdict = {}
numlist1 = []
listlength = len(numlist)
x = 1
for x in range (0,listlength):
if not numlist[x] in numdict:
numdict[numlist[x]]=1
else:
numdict[numlist[x]] = numdict[numlist[x]] + 1
numdict1 = []
numdict1 = sorted(numdict.values())
numdict2 = []
nummy = int(len(numdict1))
print(numdict1)
print(numdict)
for x in range (1, nummy):
print(x)
if numdict[x] == numdict1[x]:
numdict2.append(numdict[x])
if len(numdict2) > 1:
print("Modes =", numdict2)
else:
print("Mode =", numdict2[1])
我犯这个错误已经有一段时间了。 我的程序是用来计算平均数和用户输入的数字模式。 我的老师告诉我,这通常是由于试图添加一个字符串和一个整数。有什么帮助吗?:(
你有密码:
如果列表的长度不大于1,那么它最多是一个元素。Python(和大多数语言一样)列表的元素索引从零开始,而不是从一开始。所以这条线应该是:
但是,您还应该对列表可能为空的可能性进行编码。你知道吗
顺便说一句,在列表中使用
numdict2
这样的名称是非常混乱的,也许numlist2
会更好?你知道吗编辑: 因此,现在你有一个不同的错误,你张贴:
当用
[]
(或{}
)初始化一个列表(或字典)时,它是空的,因此它甚至没有索引0。您可以使用以下方法测试列表中的内容:如果那里有东西,这就给真;如果它是空的,这就给假。你知道吗
Python中的列表索引是从zero开始的,因此在
numdict2
List中只有一个条目的情况下,只能使用零作为索引。你知道吗相关问题 更多 >
编程相关推荐