2

I have several lists:

AllMaxMins_LC1 AllMaxMins_LC2 AllMaxMins_LC3 and so on

Now I want to go through each list like this:

for {set i 1} {$i < 10} {incr i} {
   foreach SubList $AllMaxMins_LC$i { 
   # do something
    }
}

I know that the way I try it does not work, but how can I achieve such a substitution correctly?

Lumpi
  • 2,697
  • 5
  • 38
  • 47
  • 1
    This kind of dynamic variable name scheme really calls for an array: `AllMaxMins_LC(1), AllMaxMins_LC(3), AllMaxMins_LC(3), ...`, then `foreach key [array names AllMaxMins_LC] {foreach subList $AllMaxMins_LC($key) ...` – glenn jackman Jun 10 '13 at 13:02

2 Answers2

2

You could e.g. use the set command without a second argument to access the content of the AllMaxMins_LC$i variables. E.g.:

for {set i 1} {$i < 10} {incr i} {
   set SubList [set AllMaxMins_LC$i]
   foreach element $SubList { 
     # do something
   }
}
bmk
  • 13,849
  • 5
  • 37
  • 46
1

I'm glad that you've found an answer that solves your problem.

However, if you can make your example it little more complex, we might be able to give more help. As it stands, there is no reason why you would choose to have several lists in the first place as you will apparently treat the contents of each list the same.

It's also unclear why you have a for {set i 0} {$i < 10} {incr i} loop around everything.

If you do, in fact have three lists, each with 10 elements, you might want to handle the first element from each list, then the second, then the third etc. In that case, a good bet would be

foreach maxMin_1 $AllMaxMIns_LC1 maxMin_2 $allMaxMins_LC2 maxMin_3 $allMaxMins_LC3 {
    # do somthing
}
nurdglaw
  • 2,107
  • 19
  • 37