admin管理员组

文章数量:1122832

I have a list of this form {a b} and I cannot insert anything inside the curly brackets

I tried these:

set csv [list]

lappend csv [list \
    a       \
    b]
set csv [linsert $csv 1 x]

puts "$csv"  # OUTPUT {a b} x
    

###############

set csv [list]

lappend csv [list \
    a       \
    b]

set csv [linsert $csv [llength $csv] x y]
    
    puts "$csv" # OUTPUT {a b} x y
    

###############

set csv2 [list]

lappend csv2 [list \
    a       \
    b]

 lappend csv2 [list x y]

    puts "$csv2"   # OUTPUT {a b} {x y}
    
    

###############

set csv2 [list]

lappend csv2 [list \
    a       \
    b]

 lappend csv2 y

    puts "$csv2"     #OUTPUT {a b} y

The part with "lappend csv [list " exists there since 2016 and I don't want to change. I just need to append something inside the curly braces so the desired output will be {a b x y}

I have a list of this form {a b} and I cannot insert anything inside the curly brackets

I tried these:

set csv [list]

lappend csv [list \
    a       \
    b]
set csv [linsert $csv 1 x]

puts "$csv"  # OUTPUT {a b} x
    

###############

set csv [list]

lappend csv [list \
    a       \
    b]

set csv [linsert $csv [llength $csv] x y]
    
    puts "$csv" # OUTPUT {a b} x y
    

###############

set csv2 [list]

lappend csv2 [list \
    a       \
    b]

 lappend csv2 [list x y]

    puts "$csv2"   # OUTPUT {a b} {x y}
    
    

###############

set csv2 [list]

lappend csv2 [list \
    a       \
    b]

 lappend csv2 y

    puts "$csv2"     #OUTPUT {a b} y

The part with "lappend csv [list " exists there since 2016 and I don't want to change. I just need to append something inside the curly braces so the desired output will be {a b x y}

Share Improve this question edited Nov 22, 2024 at 0:57 Razvan asked Nov 21, 2024 at 23:22 RazvanRazvan 11 bronze badge 1
  • 1 lappend csv a b? – Shawn Commented Nov 22, 2024 at 3:38
Add a comment  | 

1 Answer 1

Reset to default 1

The command lappend csv [list a b] adds a single element to the list. Since you started with an empty list, you will have a list consisting of a single element, which in turn is a list.

Now you want to insert more elements into that sublist, rather than into the overall list. The linsert and lappend commands only work on a straight forward list. They cannot reach into sublists on their own. So you will have to extract the sublist, modify it, and then put it back:

lset csv 0 [linsert [lindex $csv 0] 1 x y]

As a special case, you can take advantage of some features of lset if you only need to append a single element to the end of the sublist: The lset command can reach into sublists and it will add an element if the index exceeds the length of the list. So you can do:

lset csv 0 end+1 x

To end up with {a b x}

本文标签: insertTCLadding elements to a list withStack Overflow