为什么 Python 中的函数可以索引,而 PHP 中则不行?
我的意思并不是说这个问题是关于 Python 与 PHP 的,而是关于一般语言的。我使用 Python 和 PHP 作为示例,因为我了解它们。
在Python中,我们可以执行mytoken = mystring.split(mydelimiter)[1]
,访问由str.split
返回的列表,而无需将其分配给列表。 在 PHP 中,我们必须在访问数组之前将其放入内存中,如 $mytokenarray =explode($mydelimiter, $mystring); 所示。 $mytoken = $mytokenarray[1];。据我所知,不可能像Python那样用一条语句来做到这一点。
这种差异的背后到底发生了什么?
I don't mean for this question to be about Python vs PHP but about languages in general. I use Python and PHP as examples because I know them.
In Python we can do mytoken = mystring.split(mydelimiter)[1]
, accessing the list returned by str.split
without ever assigning it to a list.
In PHP we must put the array in memory before accessing it, as in $mytokenarray = explode($mydelimiter, $mystring); $mytoken = $mytokenarray[1];
. As far as I know it is not possible to do this in one statement as in Python.
What is going on behind this difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您尝试在 php 中执行此操作,
请注意您收到的错误:
解析错误:语法错误,意外的“[”
。这意味着 php 在尝试解析代码时会感到不安,而不是在尝试执行代码时。我怀疑这意味着 php 的语法(据我所知,它是动态生成的,尽管我真的不知道)说你不能在
statement
或之后放置 '['表达式
或者无论他们如何称呼它。相反,您可能只能将“[”放在变量后面。这是Python的语法。包含规则的 http://docs.python.org/reference/grammar.html
预告片:'(' [arglist] ')' | '['下标列表']' | '.' NAME
从那里您可以看到trailer
是atom
的一部分,它也可以包含[
。您开始意识到事情非常复杂。等等,长话短说,了解编译器,或者更好的是,为玩具语言编写一个编译器。然后你将对语言怪癖有大量的洞察力。
If you try to do this in php
notice the error you get:
Parse error: syntax error, unexpected '['
.This means that php is getting upset when it tries to parse the code, not when it tries to execute it. I suspect that means that php's grammar (which, I hear rumored, is generated on the fly though I really have no idea) says that you can't put '[' after a
statement
orexpression
or whatever they call it. Rather, you can probably only put '[' after a variable.Here's Python's grammar. http://docs.python.org/reference/grammar.html which contains the rule
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
From there you can see thattrailer
is part ofatom
which can also contain[
. You're starting to get the picture that it's pretty complicated.Blah blah blah, long story short, learn about compilers, or even better, write one for a toy language. Then you will have loads of insight into language quirks.
这是语言作者选择做出的设计决策。一般来说(当然情况并非总是如此),语言的语法越好,它的速度就越慢。典型的例子:红宝石。
It is a design decision the authors of the languages chose to make. Generally spoken (and this is of course not always the case) the nicer the syntax a language has the slower it tends to be. Case in point: Ruby.
从 5.4 版开始,PHP 就可以实现此功能。
This feature is now possible with PHP as of version 5.4.