无法删除函数调用

发布于 2024-08-07 06:43:04 字数 371 浏览 0 评论 0原文

这个问题只是出于一般的好奇心。我在处理当前项目时刚刚注意到它(令人惊讶的是我在今天之前没有遇到过)。

采取这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁许谁一生繁华 2024-08-14 06:43:04

您的意思是删除列表的最后一个元素,而不是以某种方式将 List 作为函数调用:

del List[len(List)-1]

Python 的 del 语句必须采用特定的形式,例如删除变量、list[element]、或对象.属性。这些形式可以深度嵌套,但必须遵循。它与赋值语句类似——如果您尝试分配给函数调用,您将得到类似的语法错误。

当然,在这种情况下,您真正​​想要的是

del List[-1]

this 表示列表的最后一个元素,并且更加 Pythonic。

You meant to delete the last element of the list, not somehow call List as a function:

del List[len(List)-1]

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

del List[-1]

which means the last element of the list, and is way more Pythonic.

孤寂小茶 2024-08-14 06:43:04

当您应该为列表 List[] 建立索引时,您正在调用函数 List()

在Python中,圆括号()用于调用函数,而方括号[]用于索引列表和其他序列。

尝试:

del List[len(List) - 1]

或者更好的是,利用 Python 允许负索引的事实,即从末尾开始计数:

del List[-1]

此外,您可能希望使列表的名称与内置 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:

del List[len(List) - 1]

or even better, use the fact that Python allows negative indexes, which count from the end:

del List[-1]

Also, you might want to make the list's name not so close to the built-in list type name, for clarity.

好倦 2024-08-14 06:43:04

你被允许了。但是,您使用了错误的语法。正确的语法是:

del List[-1]

请注意,“len(List) 部分是无用的。

You are allowed. However, you are using the wrong syntax. Correct syntax is:

del List[-1]

Notice that the "len(List) part is useless.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文