问题
I want to create a n*n
list in python with most of the elements initialized with None. Then I will set some elements in a for loop, but in the line I set diagonal elements to be 0
, I got a warning highlight on [j]
in PyCharm, saying:
"Unexpected type(s): (int, int) Possible types: (int, None) (slice, Iterable[None]) Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations."
I don't know where is wrong. If I change the 2d list to be all initialized as 0
in the first line, then this warning is gone. What makes None
special here?
prev = [[None] * n for i in range(n)]
for i in range(n):
for j in range(n):
if i == j:
prev[i][j] = 0
......
回答1:
This is just a warning, so your code should still run.
PyCharm tries to help you by telling what the type of variables should be, to help you to avoid error. However, sometimes it gets it wrong.
This feature is really useful in functions. For example:
def myfunction(x: str):
return x
myfunction(1)
you should see the same warning above the 1
, because it is an int
but the function expects a str
.
In you case, the type is not explicit, so likely a misjudgment from PyCharm happens.
If you change the None
from your code to a 1
or any other int
, you that the warning is gone.
prev = [[1] * n for i in range(n)]
for i in range(n):
for j in range(n):
if i == j:
prev[i][j] = 0
^
|
Warning gone
If you change the None
to 'a'
or any other str
you will see a similar warning but with (int, str)
this time.
来源:https://stackoverflow.com/questions/51800809/warning-when-python-access-2d-list-with-none-value