如何从索引开始有效地获取 Tcl 列表的其余部分?

发布于 2024-08-05 03:14:49 字数 263 浏览 4 评论 0原文

我想获取列表的特定索引后面的所有元素。这可以写成:

set foo {0 1 2 3 4 5 6 <...> n}
puts [lrange $foo 1 [llength $foo]]

然而,计算列表的长度似乎是一种浪费。如果 lrange 的最后一个参数是可选的,并且省略它意味着继续到列表末尾,那就太好了,但是,可惜今天的情况并非如此。

在 Tcl 中是否有其他方法可以有效地执行此操作,而无需计算列表的长度?

I would like to get all elements following a particular index of a list. This could be written as:

set foo {0 1 2 3 4 5 6 <...> n}
puts [lrange $foo 1 [llength $foo]]

However, it seems like a waste to compute the length of the list. It would be nice if the last argument to lrange was optional and omitting it meant to continue until the end of the list, but, alas that is not the case today.

Is there some other way of doing this efficiently in Tcl without computing the length of the list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

等风也等你 2024-08-12 03:14:49

您可以使用“end”代替“[llength $foo]”

所以...

put [lrange $foo 1 end]

You can use "end" in place of "[llength $foo]"

So...

puts [lrange $foo 1 end]

镜花水月 2024-08-12 03:14:49

杰夫很好地回答了你的实际问题。话虽如此,有一点值得注意。获取列表(实际上是底层列表)的长度是 O(1),这意味着它不需要实时时间。列表本身的长度与元数据一起存储,并且不会重新计算。唯一真正的成本是函数调用的开销。使用“end”可能仍然更快,只是没有您想象的那么快。

但是“实际上是一个列表”,我的意思是解释器当前将其视为一个列表(有更深入的解释,但不值得在这里讨论)。由于您在值上使用 [lrange],解释器必须将其内部转换为列表...因此您几乎可以保证 [llength] 的 O(1) 行为。

Jeff answered your actual question well. That being said, there is one thing worth noting. Getting the length of a list (that's actually a list under the hood) is of O(1), meaning it takes no real time. The length of the list itself is stored with the metadata, and isn't recalculated. The only real cost is the overhead of a function call. Using "end" is probably still faster, just not as much as you might have thought.

But "actually a list under the hood", I mean that the interpreter is currently treating it as a list (there a deeper explanation, but not worth going into here). Since you are using [lrange] on the value, the interpreter must convert it's internal to a list... so you're pretty much guaranteed the O(1) behavior of [llength].

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