错误消息“'int' 对象没有属性 '__getitem__'”

Error message "'int' object has no attribute '__getitem__'"

import random

numbers = []
for i in range(301):
    numbers.append(random.randint(1,600))

g=0
u=0

for i in numbers:
    if i[-1]=="1" or i[-1]=="3" or i[-1]=="5" or i[-1]=="7" or i[-1]=="9":
        u +=1
    else:
        g +=1
print g
print u

它总是给我这样的错误:

TypeError: 'int' object has no attribute '__getitem__'

我只是一个初学者,所以我真的不明白,这里的问题在哪里...所以感谢您的帮助...

你让 i 成为 numbers 的一个元素。 numbers 的元素是 int。您不能索引整数:5[3] ← 没有意义。

Python 中的索引是通过方法 __getitem__() 完成的,因此 Python 尝试调用 5.__getitem__(3)(不存在)。这就是错误消息的来源。

您可能想要的是对整数进行字符串化:

str(i)[-1]

获取数字的最后一位(作为字符)。

但是因为你比较的是 1, 3, 5, 7, 9 我猜你想测试是不是奇数。这样做更简单:

i % 2 == 1