【问题标题】:Take the highest value of List X, and compare it with List Y ,and find the highest values in Y add it to new list using TCL取 List X 的最大值,并与 List Y 进行比较,找到 Y 中的最大值,使用 TCL 将其添加到新列表中
【发布时间】:2020-09-26 03:44:10
【问题描述】:

我有两个列表,假设 X 和 Y。找到列表 X 的最大值,并将其与列表 Y 的值进行比较,如果 Y 的值大于 X,则使用 TCL 将其添加到新列表中。

set X[list 1.2156476714e-04 1.1284486163e-03 1.9818406145e-01 2.9287846814e-04 2.0217831320e-04]

set Y[list 1.2156476714e-04 1.1284486163e-03 4.5386226702e-02 4.4706815970e-02 8.4928524302e-03 6.0775778365e-03 3.1041158763e-03 1.5045881446e-01 4.1016753016e-04 1.1655993148e-03 1.8736355969e-03 2.9444883694e-02 2.5420340535e-02 2.0819682049e-03 9.5297318694e-03 8.5498101043e-04 1.5580140825e-02 8.0796216935e-03 4.8684447393e-02 1.6464813962e-01]

取 List X 的最大值,将其与 List Y 的每个值进行比较。如果 List Y 的值大于 X 值,则将其添加到新列表中。

【问题讨论】:

  • 您的预期答案是什么?
  • 到目前为止你尝试过什么?你能找到列表中的最大数字吗?
  • 你想找出 Y 中大于 X 中最大元素的所有元素吗?鉴于 Y 中的所有元素都大于max(X),您的预期输出似乎没有多大意义

标签: list tcl list-comparison


【解决方案1】:

找到事物的最大值是 max() 函数(在 expr 中)的问题除了我们想将它应用到一个列表中,所以我们直接调用函数的实现命令我们可以通过扩展输入值列表:

set max_X [tcl::mathfunc::max {*}$X]
#          ^^^^^^^^^^^^^^^    ^^^ Expansion: pass what follows as many arguments
#          Function calls get transformed into invokes of commands in the tcl::mathfunc namespace

对于第二个列表的过滤,写一个程序是最清楚的。可以使用foreachlmap 实现过滤;后者实际上只是一个foreach,如果它们是正常结果,它会收集这些值,而不是像continue 这样的东西。

这两个版本的过程基本上做同样的事情:

proc filter_greater_than {value list} {
    lmap x $list {expr {$x > $value ? $x : [continue]}}
}
proc filter_greater_than {value list} {
    set result {}
    foreach x $list {
        if {$x > $value} {
            lappend result $x
        }
    }
    return $result
}

然后你可以像这样使用这个过程:

set new_list [filter_greater_than $max_X $Y]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2022-11-22
    相关资源
    最近更新 更多