0

Hi i have a list of parent-child items as follows :

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}};

Now i am trying to achieve couple of tasks here.

  1. Create a new list of unique items from the above list $mylist.
  2. Create an array with keys as the unique items from my newlist and values as some data that i have available.

So i created a new list using the below code.

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

which gave me output as

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

and then i did lsort -unique

set newlist [lsort -unique $newlist];

which gave me the unique list 1:0 10:0 11:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0

Now I create the array as below

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} 
  ...
}

Which basically gives me what I wanted to achieve, but I was wondering if there is a better way to achieve the same task. For example, I was thinking if there is a better way of creating newlist from mylist, basically the unique newlist from mylist items??

2 Answers 2

1

Off the top of my head I might have written something like:

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

Or you might prefer some variables rather than the nested commands.

Sign up to request clarification or add additional context in comments.

Comments

1

Using an array directly is another way to get a list of unique values (cannot have duplicate array keys)

% 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

You can reassign the array values as you wish.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.