PyCharm 中的列表引发意外类型警告

Hui*_*don 5 python pycharm python-3.x

言归正传,下面是在 PyCharm 中会引发错误的示例代码:

list1 = [0] * 5
list1[0] = ''
list2 = [0 for n in range(5)]
list2[0] = ''
Run Code Online (Sandbox Code Playgroud)

然后 PyCharm 在第 2 行和第 4 行都返回错误,如下所示:

Unexpected type(s):(int, str)Possible type(s):(SupportsIndex, int)(slice, Iterable[int])
Run Code Online (Sandbox Code Playgroud)

运行代码不会导致任何错误,但当我编码时,PyCharm 不断引发上述消息。

为什么 PyCharm 会给出这个错误,我如何用最干净的代码解决这个错误?

Ale*_*hen 6

在您的情况下,PyCharm 看到您的第一行并认为列表的类型是List[int]。我的意思是它是一个整数列表。

您可能会发现您的列表不是 int 类型的,并且可以通过这种方式接受任何值:

from typing import Any, List

list1: List[Any] = [0] * 5
list1[0] = ''
Run Code Online (Sandbox Code Playgroud)

我使用打字模块只是为了解释这个想法。这是一个简单的方法来声明 list1 只是一个列表:

list1: list = [0] * 5
list1[0] = ''
Run Code Online (Sandbox Code Playgroud)

还要考虑使用尽可能严格的类型。它可以帮助您防止错误。

如果您同时需要字符串和整数,请使用:

from typing import List, Union

list1: List[Union[int, str]] = [0] * 5
# Starting from Python 3.10 you may use List[int|str] instead 
Run Code Online (Sandbox Code Playgroud)

此处的文档: https: //docs.python.org/3/library/typing.html