当python访问具有无值的二维列表时发出警告 [英] warning when python access 2d list with None value

查看:81
本文介绍了当python访问具有无值的二维列表时发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中创建一个 n*n 列表,其中大部分元素都用 None 初始化.然后我将在 for 循环中设置一些元素,但是在我将对角线元素设置为 0 的行中,我在 PyCharm 中的 [j] 上得到了一个警告突出显示,说:

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:

"意外类型:(int, int) 可能的类型:(int, None)(切片,Iterable[None]) 检查信息:此检查检测类型错误在函数调用表达式中.由于动态调度和鸭子类型,这在有限但有用的情况下是可能的.种类函数参数可以在文档字符串或 Python 3 中指定函数注释."

"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."

我不知道哪里错了.如果我将第一行中的 2d 列表更改为全部初始化为 0 ,则此警告消失了.是什么让 None 在这里特别?

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
        ......

推荐答案

这只是一个警告,因此您的代码仍应运行.

This is just a warning, so your code should still run.

PyCharm 试图通过告诉您变量的类型应该是什么来帮助您,以帮助您避免错误.但是,有时会出错.

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)

您应该在 1 上方看到相同的警告,因为它是一个 int 但该函数需要一个 str.

you should see the same warning above the 1, because it is an int but the function expects a str.

在你的情况下,类型不是明确的,所以可能会发生 PyCharm 的错误判断.

In you case, the type is not explicit, so likely a misjudgment from PyCharm happens.

如果您将代码中的 None 更改为 1 或任何其他 int,则警告消失了.

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

如果您将 None 更改为 'a' 或任何其他 str,您将看到类似的警告,但带有 (int, str) 这次.

If you change the None to 'a' or any other str you will see a similar warning but with (int, str) this time.

这篇关于当python访问具有无值的二维列表时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆