使用 TCL 从列表中查找给定值的索引号

Find the index number of given value from the list using TCL

需要从列表中找到给定值的索引号。我有一个列表中的值,但我需要找到该值的索引号。

set i 0.0001646481396164745
set X [list 1.215647671415354e-7 1.1284486163276597e-6 4.538622670224868e-5 4.4706815970130265e-5 8.492852430208586e-6 6.077577836549608e-6 3.1041158763400745e-6 0.00015045881445985287 4.1016753016265284e-7 1.165599314845167e-6 1.8736355968940188e-6 2.9444883693940938e-5 2.5420340534765273e-5 2.0819682049477706e-6 9.529731869406532e-6 8.549810104341304e-7 1.558014082547743e-5 8.079621693468653e-6 4.868444739258848e-5 0.0001646481396164745]

必须使用 TCL.

找到 列表 X 中 i 的索引值

可以用lsearch轻松解决:

set c [lsearch $X $i]

如果您要在列表中查找浮点值,而您只知道 近似值,则不能使用 lsearch。相反,你必须自己做:

proc findApprox {theList theValue {epsilon 1e-9}} {
    set idx 0
    foreach x $theList {
        # Found if the difference between the list item and the target is less than epsilon
        if {abs($theValue - $x) < $epsilon} {
            return $idx
        }
        incr idx
    }
    return -1
    # Or [error "not found"] if you prefer
}

set x [findApprox $X $i]

注意 epsilon 可选参数。那是因为您必须获得多近取决于对输入数据域的了解;这不是一个基本算法可以轻松为您确定的东西。