[英]TypeError: 'generator' object is not subscriptable error
This is basic code, but it is throwing a 'TypeError: 'generator' object is not subscriptable' on the "print(numList[index])."这是基本代码,但它会在“print(numList[index])”上抛出“TypeError: 'generator' object is not subscriptable'”。 Can someone please help me get rid of this error.
有人可以帮我摆脱这个错误。
numbers = input("Enter 9 Numbers: ")
numList = (int(x) for x in numbers.split())
index = 0
for count in range(0, 10):
if count % 3 == 0:
print(numList[index])
else:
print(numList[index])
index+=1
To make numList
an array instead of a generator change the brackets from (
to [
要使
numList
成为数组而不是生成器,请将括号从(
更改为[
numList = [int(x) for x in numbers.split()]
Regardless of whether it is an array or a generator you can iterate over the numList
like the following无论是数组还是生成器,您都可以像下面这样遍历
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))
The error was being thrown when I was converting the string input into an integer list.当我将字符串输入转换为整数列表时,错误被抛出。 To fix it, I used a loop and converted each index into an integer.
为了修复它,我使用了一个循环并将每个索引转换为一个整数。
The line: numList = (int(x) for x in numbers.split())
该行:
numList = (int(x) for x in numbers.split())
Creates a generator, which only returns a single value each time it is called (see https://realpython.com/introduction-to-python-generators/ ).创建一个生成器,它每次被调用时只返回一个值(参见https://realpython.com/introduction-to-python-generators/ )。
What you probably want is a list comprehension, which will create a new list that you can index: numList = [int(x) for x in numbers.split()]
您可能想要的是一个列表
numList = [int(x) for x in numbers.split()]
,它将创建一个您可以索引的新列表: numList = [int(x) for x in numbers.split()]
Once you do this, you'll notice that your range goes beyond the length of numList
(9), but that's also an easy fix:一旦你这样做,你会注意到你的范围超出了
numList
(9) 的长度,但这也是一个简单的修复:
for count in range(0, 9):
Another option would be to keep the generator and do something like this:另一种选择是保留生成器并执行以下操作:
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?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.