【问题标题】:Unique list elements in TclTcl 中的唯一列表元素
【发布时间】:2022-12-03 05:26:48
【问题描述】:

我有两个等长的 Tcl 列表,uvu 中的许多条目已知是相同的。对于 u 中的每个唯一条目,我想对 v 中的相应条目进行平均。所以,如果我的列表是{1 2 1 2}{1 2 3 4},输出应该是{1 2}(只有u中唯一的条目)和{2 3},其中2个来自(1+3)/2,3个来自@ 987654332@。

我尝试了以下方法:

set unique [lsort -unique $u]
foreach i $unique {
  set ave 0; set N 0
  foreach j $u k $v {
    if {$i == $j} {set ave [expr {$ave+$k}]}
  }
  lappend w [expr {$ave/$N}]
} 

这可行,但对于较大的列表来说太慢了。有谁知道更有效的方法吗?

提前致谢!

【问题讨论】:

    标签: tcl


    【解决方案1】:

    为了更有效地对两个列表中的相应条目进行平均,您可以使用 Tcl 中的数组数据结构。数组数据结构允许您存储由键索引的值,并提供访问和更新值的有效方法:

    # Create an array to store the sums of the corresponding entries in v
    array set sums {}
    
    # Loop through the entries in u and add the corresponding entries in v to the array
    foreach i $u j $v {
      set sums($i) [expr {$sums($i) + $j}]
    }
    
    # Create an empty list to store the results
    set result {}
    
    # Loop through the unique entries in u and compute the average of the corresponding entries in v
    foreach i [lsort -unique $u] {
      lappend result [expr {$sums($i) / [llength $u]}]
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 1970-01-01
      • 2011-05-23
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多