I have a list in Tcl as:
set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
then how could I get the element based on the index of list? for example:
I want to get the second element of this list? or the sixth one of this list?
I have a list in Tcl as:
set list1 {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9}
then how could I get the element based on the index of list? for example:
I want to get the second element of this list? or the sixth one of this list?
Just use split and loop?
foreach n [split $list1 ","] {
puts [string trim $n] ;# Trim to remove the extra space after the comma
}
[split $list1 ","]
returns a list containing 0x1 { 0x2} { 0x3} { 0x4} { 0x5} { 0x6} { 0x7} { 0x8} { 0x9}
The foreach
loop iterates over each element of the list and assign the current element to $n
.
[string trim $n]
then removes trailing spaces (if any) and puts prints the result.
EDIT:
To get the nth element of the list, use the lindex
function:
% puts [lindex $list1 1]
0x2
% puts [lindex $list1 5]
0x6
The index is 0-based, so you have to remove 1 from the index you need to pull from the list.
You "should" be using lindex for that. But from your question I have te impression that you do not want the "," to be present in the element extracted. You don't need the "," to separate the list. Just the blank space will do.
> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4
© 2022 - 2024 — McMap. All rights reserved.