首页 > 解决方案 > TCL - 在浮动值列表中选择第 n 项

问题描述

有谁知道在包含浮动值的列表中选择特定值的方法(即,与用于列表中整数的Lindex等效的方法)?

标签: tcl

解决方案


Tcl 的lindex命令可以在任意列表上工作,但索引本身必须是整数或相对结束(例如,end-1)。列表中的值绝对可以是浮点数(或任何其他值,包括字符串和列表以及变量名称和代码片段和数据库句柄……)。

set theList [list 1.23 2.34 3.45 [expr {4.56 + 5.67}]]
puts [lindex $theList 3]

索引必须是整数,因为它们在逻辑上从列表的开头计算位置(或者从列表的末尾开始,当然是相对的)。使用浮点数计算位置完全没有意义。


如果您试图在浮点数的排序列表中查找浮点数的所属位置,则该lsearch命令是正确的工具(具有以下选项)。

set idx [lsearch -sorted -real -bisect $theList 6.78]

# Now $idx is the index where the value is *or* the index before where it would be inserted
# In particular, $idx+1 indicates the first element later than the value

上面的选项是:

  • -sorted— 告诉lsearch命令列表已排序(因此它可以使用二进制搜索算法而不是线性算法)
  • -real— 告诉lsearch命令它正在使用浮点比较
  • -bisect— 告诉lsearch命令找到值的槽(-1如果它不存在则不返回)

推荐阅读