【问题标题】:TypeError: 'generator' object is not subscriptable errorTypeError:“生成器”对象不可下标错误
【发布时间】:2020-01-16 04:07:43
【问题描述】:

这是基本代码,但它在“print(numList[index])”上抛出“TypeError: 'generator' object is not subscriptable”。有人可以帮我摆脱这个错误。


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

【问题讨论】:

    标签: python


    【解决方案1】:

    当我将字符串输入转换为整数列表时引发错误。为了解决这个问题,我使用了一个循环并将每个索引转换为一个整数。

    【讨论】:

      【解决方案2】:

      行: numList = (int(x) for x in numbers.split())

      创建一个生成器,每次调用它时只返回一个值(参见https://realpython.com/introduction-to-python-generators/)。

      您可能想要的是一个列表推导,它将创建一个您可以索引的新列表: numList = [int(x) for x in numbers.split()]

      执行此操作后,您会注意到您的范围超出了 numList (9) 的长度,但这也很容易解决:

      for count in range(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?
      

      【讨论】:

        【解决方案3】:

        要使 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))
        
        

        【讨论】:

          猜你喜欢
          • 2020-08-18
          • 2011-09-11
          • 1970-01-01
          • 2019-02-10
          • 1970-01-01
          • 2015-12-09
          • 2014-12-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多