当我将列表分配给变量时,为什么 Pycharm 给我的提示是 "this list creation could be rewritten as a list literal"?
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"?
我是 Python 初学者,有一个难题。
当我这样写代码时:
lst = [1, 2, 3, 4]
Pycharm提示我是"this list creation could be rewritten as a list literal"。
但是如果换成
lst = list([1, 2, 3, 4])
Pycharm什么也没说。谁能告诉我为什么?
像 lst = [1, 2, 3, 4]
这样的代码在 Python 中合法吗?我可以忽略提示吗?
检查您的代码,确保您在其他地方没有 lst
作为 lst=[]
。
如果您键入以下内容:
lst= []
# more code
lst = [1, 2, 3, 4]
您将收到您得到的提示。如果你保持这种方式,你不会 运行 遇到问题,但这是不好的做法。
在这两种情况下,您使用函数来更改变量:list()
和 append()
。在上一个中,您只是明确地重新定义了变量。
另一个不恰当的例子:
a = 7
# some code that has nothing to do with "a" or uses it
a = 8
刚开始设置 a = 8
。无需存储a = 7
.
在 Python 中编写这样的代码是完全合法的。但是,编写代码
lst = [1, 2, 3, 4, 12]
会比
"better"
lst = [1, 2, 3, 4]
... # code has nothing do to with lst
lst.append(12)
一般来说,前者比后者有更好的性能,但如果后者在你的 case/you 中更具可读性并且有充分的理由这样做,那么你可以忽略 PyCharm提示。
如果这让您感到困扰,您可以在
中关闭此检查
"PyCharm->settings->editor->inspection->Python->List creation could be..."
我是 Python 初学者,有一个难题。 当我这样写代码时:
lst = [1, 2, 3, 4]
Pycharm提示我是"this list creation could be rewritten as a list literal"。 但是如果换成
lst = list([1, 2, 3, 4])
Pycharm什么也没说。谁能告诉我为什么?
像 lst = [1, 2, 3, 4]
这样的代码在 Python 中合法吗?我可以忽略提示吗?
检查您的代码,确保您在其他地方没有 lst
作为 lst=[]
。
如果您键入以下内容:
lst= []
# more code
lst = [1, 2, 3, 4]
您将收到您得到的提示。如果你保持这种方式,你不会 运行 遇到问题,但这是不好的做法。
在这两种情况下,您使用函数来更改变量:list()
和 append()
。在上一个中,您只是明确地重新定义了变量。
另一个不恰当的例子:
a = 7
# some code that has nothing to do with "a" or uses it
a = 8
刚开始设置 a = 8
。无需存储a = 7
.
在 Python 中编写这样的代码是完全合法的。但是,编写代码
lst = [1, 2, 3, 4, 12]
会比
"better"lst = [1, 2, 3, 4]
... # code has nothing do to with lst
lst.append(12)
一般来说,前者比后者有更好的性能,但如果后者在你的 case/you 中更具可读性并且有充分的理由这样做,那么你可以忽略 PyCharm提示。
如果这让您感到困扰,您可以在
中关闭此检查"PyCharm->settings->editor->inspection->Python->List creation could be..."