无法删除函数调用
这个问题只是出于一般的好奇心。我在处理当前项目时刚刚注意到它(令人惊讶的是我在今天之前没有遇到过)。
采取这段代码:
List = ["hi","stack","over","flow","how","you","doing"]
del List(len(List)-1)
错误:
SyntaxError: can't delete function call
我不明白为什么不允许您通过引用函数调用来删除列表的索引?我是闭嘴并接受你做不到还是我做的事情根本就是错误的?
如果有一个简单的答案,我深表歉意,但要么谷歌的帮助越来越小,要么这太明显了,我需要帮助。
This question is just out of general curiosity. I've just noticed it when working on my current project (surprisingly I haven't came across before today).
Take this code:
List = ["hi","stack","over","flow","how","you","doing"]
del List(len(List)-1)
Error:
SyntaxError: can't delete function call
I don't understand why you aren't allowed to delete an index of a list by referencing a call to a function? Do I just shut up and accept you can't do it or am I doing something fundamentally wrong?
I apologise if there is an easy answer to this but either Google is getting less helpful or this is so blatantly obvious I need help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的意思是删除列表的最后一个元素,而不是以某种方式将
List
作为函数调用:Python 的
del
语句必须采用特定的形式,例如删除变量、list[element]、或对象.属性。这些形式可以深度嵌套,但必须遵循。它与赋值语句类似——如果您尝试分配给函数调用,您将得到类似的语法错误。当然,在这种情况下,您真正想要的是
this 表示列表的最后一个元素,并且更加 Pythonic。
You meant to delete the last element of the list, not somehow call
List
as a function:Python's
del
statement must take specific forms like deleting a variable, list[element], or object.property. These forms can be nested deeply, but must be followed. It parallels the assignment statement -- you'll get a similar syntax error if you try to assign to a function call.Of course, what you really want in this case is
which means the last element of the list, and is way more Pythonic.
当您应该为列表
List[]
建立索引时,您正在调用函数List()
。在Python中,圆括号
()
用于调用函数,而方括号[]
用于索引列表和其他序列。尝试:
或者更好的是,利用 Python 允许负索引的事实,即从末尾开始计数:
此外,您可能希望使列表的名称与内置
list
类型名称不太接近,为了清楚起见。You are calling a function
List()
when you should be indexing a list,List[]
.In Python, Round parenthesis,
()
, are used to call functions, while square brackets,[]
are used to index lists and other sequences.Try:
or even better, use the fact that Python allows negative indexes, which count from the end:
Also, you might want to make the list's name not so close to the built-in
list
type name, for clarity.你被允许了。但是,您使用了错误的语法。正确的语法是:
请注意,“len(List) 部分是无用的。
You are allowed. However, you are using the wrong syntax. Correct syntax is:
Notice that the "len(List) part is useless.