Python 类型错误:';发电机&x27;对象不可下标错误
这是基本代码,但它在“print(numList[index])上抛出了一个“TypeError:”generator“object is not subscriptable”(对象不可下标)。有人能帮我消除这个错误吗Python 类型错误:';发电机&x27;对象不可下标错误,python,Python,这是基本代码,但它在“print(numList[index])上抛出了一个“TypeError:”generator“object is not subscriptable”(对象不可下标)。有人能帮我消除这个错误吗 数字=输入(“输入9个数字:”) numList=(整数(x)表示数字中的x.split() 索引=0 对于范围(0,10)内的计数: 如果计数%3==0: 打印(numList[索引]) 其他: 打印(numList[索引]) 指数+=1 要使numList成为数组而不是生成
数字=输入(“输入9个数字:”)
numList=(整数(x)表示数字中的x.split()
索引=0
对于范围(0,10)内的计数:
如果计数%3==0:
打印(numList[索引])
其他:
打印(numList[索引])
指数+=1
要使numList
成为数组而不是生成器,请将括号从(
更改为[
numList = [int(x) for x in numbers.split()]
无论是数组还是生成器,您都可以像下面这样迭代numList
for num in numList:
if num % 3 == 0:
print("{} is multiple of 3".format(num))
else:
print("{} is not multiple of 3".format(num))
将字符串输入转换为整数列表时引发错误。为了解决此问题,我使用了一个循环并将每个索引转换为整数。行:
numList=(int(x)表示数字中的x.split())
创建一个生成器,该生成器每次调用时仅返回一个值(请参见)
您可能需要的是列表理解,它将创建一个新的列表,您可以索引:
numList=[int(x)表示数字中的x.split()]
一旦您这样做,您会注意到您的范围超出了numList
(9)的长度,但这也是一个简单的解决方法:
用于范围(0,9)内的计数:
另一种选择是保留生成器并执行以下操作:
numbers = input("Enter 9 Numbers: ")
numList = (int(x) for x in numbers.split())
for count, num in enumerate(numList):
if count % 3 == 0:
print(num)
else:
print(num) #eventually you what to do something different here?