概述
Normally Python throws NameError if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "", line 1, in
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
>>> dict[0]
Traceback (most recent call last):
File "", line 1, in
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
2、TypeError: 'int' object is not subscriptable
I'm trying to create a simple program that tells you your lucky number according to numerology. I keep on getting this error:
File "number.py", line 12, in
sumln = (int(sumall[0])+int(sumall[1]))
TypeError: 'int' object is not subscriptable
My script is:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = (int(birthday[0])+int(birthday[1]))
sumd = (int(birthday[3])+int(birthday[4]))
sumy= (int(birthday[6])+int(birthday[7])+int(birthday[8])+int(birthday[9]))
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln`
If you want to sum the digit of a number, one way to do it is using sum() + a generator expression:
sum(int(i) for i in str(155))
I modified a little your code using sum(), maybe you want to take a look at it:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln
最后
以上就是奋斗季节为你收集整理的python type object is not_python: "TypeError: 'type' object is not subscriptable"的全部内容,希望文章能够帮你解决python type object is not_python: "TypeError: 'type' object is not subscriptable"所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复