在tcl中创建列表中的数组

时间:2014-11-07 21:15:34

标签: arrays list tcl

您好我有一个父子项目列表如下:

set mylist {{1:0 2:0} {2:0 3:0} {3:0 4:0} {3:0 5:0} {3:0 6:0} {3:0 7:0}
            {4:0 8:0} {5:0 9:0} {4:0 10:0} {5:0 11:0}};

现在我想在这里完成几项任务。

  1. 从上面的列表$ mylist中创建一个新的唯一项列表。
  2. 创建一个数组,其中键作为我的新列表中的唯一项,值作为我可用的一些数据。
  3. 所以我使用下面的代码创建了一个新列表。

    set newlist [list];
    foreach item $mylist {
      lappend newlist [lindex $item 0]; 
      lappend newlist [lindex $item 1]; 
    }
    

    给了我输出

    1:0 2:0 2:0 3:0 3:0 4:0 3:0 5:0 3:0 6:0 3:0 7:0 4:0 8:0 5:0 9:0 4:0 10:0 5:0 11:0
    

    然后我做了lsort -unique

    set newlist [lsort -unique $newlist];
    

    给了我唯一的列表1:0 10:0 11:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0

    现在我按如下所示创建数组

    array set newarr {
      [lindex $newlist 0] {list of values} 
      [lindex $newlist 1] {list of values} 
      [lindex $newlist 2] {list of values} 
      [lindex $newlist 3] {list of values} 
      ...
    }
    

    这基本上给了我想要实现的目标,但我想知道是否有更好的方法来实现同样的任务。例如,我在想是否有更好的方法从mylist创建新列表,基本上是来自mylist项目的唯一新列表?

2 个答案:

答案 0 :(得分:1)

在我的脑海中,我可能写了类似的东西:

foreach item [lsort -unique [concat {*}$mylist]] {
    set newarr($item) {list of values}
}

或者您可能更喜欢某些变量而不是嵌套命令。

答案 1 :(得分:1)

直接使用数组是另一种获取唯一值列表的方法(不能有重复的数组键)

% foreach pair $mylist {lassign $pair x y; incr ary($x); incr ary($y)}
% parray ary
ary(10:0) = 1
ary(11:0) = 1
ary(1:0)  = 1
ary(2:0)  = 2
ary(3:0)  = 5
ary(4:0)  = 3
ary(5:0)  = 3
ary(6:0)  = 1
ary(7:0)  = 1
ary(8:0)  = 1
ary(9:0)  = 1

您可以根据需要重新分配数组值。