tcl - TCL - 在浮动值列表中选择第 n 项
问题描述
有谁知道在包含浮动值的列表中选择特定值的方法(即,与用于列表中整数的Lindex等效的方法)?
解决方案
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
如果它不存在则不返回)
推荐阅读
- php - Laravel eloquent 对查询结果运行查询
- java - BrowserstackLocal.stop() 挂起 Docker 容器
- javascript - 反应输入类型文件 onChange 不触发
- mysql - 将数据集存储在 mysql 数据库中 - 6000 个条目
- python-3.x - Python脚本中的SQLite占位符错误
- c# - C# MVC 在 Visual Studio 控制台中显示已调用的方法和部分
- python - python Ubuntu:打开的文件太多 [eventpoll]
- php - PHP 如何让单选按钮工作
- c++ - 具有最小堆的 C++ 二叉树
- python - 类型错误:tree.py 中的“float”和“str”实例之间不支持“<”