list 如何从 Tcl 中的列表中获取价值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19136611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value from a list in Tcl?
提问by user2131316
I have a list in Tcl as:
我在 Tcl 中有一个列表:
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?
我想得到这个列表的第二个元素?还是这个列表的第六个?
回答by Jerry
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}
[split $list1 ","]
返回一个包含 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
.
该foreach
循环遍历列表中的每个元素和分配当前的元素$n
。
[string trim $n]
then removes trailing spaces (if any) and puts prints the result.
[string trim $n]
然后删除尾随空格(如果有)并 puts 打印结果。
EDIT:
编辑:
To get the nth element of the list, use the lindex
function:
要获取列表的第n个元素,请使用以下lindex
函数:
% 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.
该索引是基于 0 的,因此您必须从需要从列表中提取的索引中删除 1。
回答by Sagar Shahabade
Just do
做就是了
lindex $list 2
you will get
你会得到
0x3
回答by thiago santos sobrinho
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.
您“应该”为此使用 lindex 。但是从您的问题中,我的印象是您不希望“,”出现在提取的元素中。您不需要“,”来分隔列表。只要空白就行了。
> set list1 {0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9}
> 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9
> lindex $list1 3
> 0x4