Python 当我将列表分配给变量时,为什么 Pycharm 会提示我“此列表创建可以重写为列表文字”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31063384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:25:17  来源:igfitidea点击:

When I assign a list to variable why Pycharm give me a prompt that is "this list creation could be rewritten as a list literal"?

pythonlistpycharm

提问by russell

I am a Python beginner and have a puzzle. When I write code like this:

我是 Python 初学者并且有一个谜题。当我写这样的代码时:

lst = [1, 2, 3, 4]

Pycharm give me a prompt that is "this list creation could be rewritten as a list literal". But if it's replaced by

Pycharm 给我一个提示,即“此列表创建可以重写为列表文字”。但是如果换成

lst = list([1, 2, 3, 4])

Pycharm doesn't say anything. Who could tell me why?

Pycharm 什么也没说。谁能告诉我为什么?

Is this code like lst = [1, 2, 3, 4]legal in Python? Can I ignore prompt?

这段代码lst = [1, 2, 3, 4]在 Python 中是否合法?我可以忽略提示吗?

采纳答案by Leb

Check your code to make sure you don't have lstsomewhere else as lst=[].

检查您的代码以确保您没有lst其他地方作为lst=[].

If you type the following:

如果您键入以下内容:

lst= []
# more code
lst = [1, 2, 3, 4]

You'll receive the prompt you got. You won't run into problems if you keep it that way but it's bad practice.

你会收到你得到的提示。如果你保持这种方式,你不会遇到问题,但这是不好的做法。

In those two cases you are using a function to change the variable: list()and append(). In the previous one where you're just redefining the variable explicitly.

在这两种情况下,您正在使用函数来更改变量:list()append()。在上一个中,您只是显式地重新定义了变量。

Another improper example:

另一个不恰当的例子:

a = 7
# some code that has nothing to do with "a" or uses it
a = 8

Just set a = 8to begin with. No need to store a = 7.

a = 8开始。无需存储a = 7

回答by Shawn

It's totally legal to write code like that in Python. However, writing code like

在 Python 中编写这样的代码是完全合法的。但是,编写代码如下

lst = [1, 2, 3, 4, 12]

would be "better" than

会比

lst = [1, 2, 3, 4]
... # code has nothing do to with lst
lst.append(12)

In general, the former one would have better performance than the latter one, but if the latter one is more readable in your case/you have a good reason doing that, then you can ignore the PyCharm prompt.

一般来说,前一个会比后一个有更好的性能,但如果后一个在你的情况下更具可读性/你有充分的理由这样做,那么你可以忽略 PyCharm 提示。

If it bothers you, you can turn this inspection off in

如果它打扰您,您可以在

"PyCharm->settings->editor->inspection->Python->List creation could be..."

“PyCharm->settings->editor->inspection->Python->List 创建可能是……”