Forum Discussion
insert values in nested lists except last
I want to insert rows into a list / table , i have used lists here for clarity, but not the last so
{ { 1,2,3}, {1,2,3} , { 1,2,3} } = { 1,2,3,"X"} , {1,2,3,"X"} , {1,2,3}}
I have two methods which work, but would be interested in any other approaches,
let
Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}},
p = List.Positions( List.RemoveLastN( Source,1)) ,
addlists = List.Transform( p, (x)=> Source {x} & {""} ) & List.LastN( Source ,1)
in
addlistslet
Or
Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}},
transfrom = List.Transform( Source, (x)=> List.InsertRange( x, List.Count(x), {""} )), result = List.ReplaceRange( transfrom, List.Count( transfrom) -1, 1, List.LastN( Source,1) )
in
result
I did try putting these in code quotes, but it did not seem to work, so sorry for that.
Richard
4 Replies
- ShivekMaharajImpactful Individual
Hi Dicken,
You can simplify your first approach by transforming everything except the last item directly, then appending the last item unchanged:
let
Source = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}},
Result =
List.Transform(
List.RemoveLastN(Source, 1),
each _ & {"X"}
)
& List.LastN(Source, 1)
in
ResultThis gives:
{{1,2,3,"X"}, {4,5,6,"X"}, {7,8,9,"X"}, {10,11,12}}List.RemoveLastN removes the final nested list, List.Transform appends "X" to everything remaining, and List.LastN adds the untouched final item back.
It avoids needing the positions or a subsequent List.ReplaceRange.
- slorinSuper User
Hi,
= List.Transform(
List.Zip({
alist,
List.Repeat({{"X"}}, List.Count(alist)-1) & {{}} }),
List.Combine)Stéphane
- slorinSuper User
To avoid adding a "null" to the last item
= List.Transform(
List.Zip({
List.RemoveLastN(Source, 1),
List.Repeat({{"X"}}, List.Count(Source)-1)}),
List.Combine)
& {List.Last(Source)}
- ZhangKunSuper User
let Source = { {1,2,3}, {4,5,6}, {7,8,9} , {10,11,12}}, p = List.Count(Source) - 1, addlists = List.Generate( ()=> 0, each _ <= p, each _ + 1, each if _ = p then Source{p} else Source{p} & {"X"} ) in addlists