类型错误:“'types.GenericAlias'对象不可迭代”

Gab*_*eed 6 python typeerror

我正在做的一个项目是将文本转换为数字。(例如,“hello world”将转换为“8 5 12 12 15 27 23 15 18 12 4”)。

在我的代码的第 10 行中,for 循环导致以下错误消息:

Traceback (most recent call last):
  File "C:\Users\gabri\PycharmProjects\padding\main.py", line 15, in <module>
    converter(plaintext)
  File "C:\Users\gabri\PycharmProjects\padding\main.py", line 10, in converter
    for n in plaintext:
TypeError: 'types.GenericAlias' object is not iterable

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

alphabet = ("a","b","c","d","e","f","g","h","i","j","k","l","m",'n',"o","p","q","r",'s','t','u','v','w','x','y','z')


def getplaintext():
    global plaintext
    plaintext = list[input("Enter plaintext:.....")]
    print(plaintext)

def converter(plaintext):
    for n in plaintext:
        print(n)


getplaintext()
converter(plaintext)
Run Code Online (Sandbox Code Playgroud)

有谁知道是什么导致了这个错误?

Car*_*ate 13

您需要使用listwith (),而不是[]

plaintext = list(input("Enter plaintext:....."))  # With ()
Run Code Online (Sandbox Code Playgroud)

在较新版本的 Python 中,list 可以直接暗示容器类型来指定容器所保存的元素的类型。通过在此处使用方括号,您可以创建列表的通用类型提示(“通用别名”)。列表的通用别名是不可迭代的,因为它实际上不是列表。这就是导致你的错误的原因。

  • 这可能是一个错字,但我认为应该回答。这是 Python 中的一个新错误,因此我们可能会开始看到有关它的问题。 (3认同)