Adding elements to some sublists of unequal length
Fold[Insert[#1, Last[#2], {First[#2], -1}] &, a, b]
Perhaps something like this:
ReplacePart[a, #1 -> Append[a[[#1]], #2]& @@@ b]
If data are large and speedup is needed you might want to try Join
ReplacePart[a, #1 -> Join[a[[#1]], {#2}] & @@@ b]
In case you want value of a
to be the new list with added elements, you whether can use AppendTo
:
ReplacePart[a, #1 -> AppendTo[a[[#1]], #2] & @@@ b]
or simply reassign:
a = ReplacePart[a, #1 -> Append[a[[#1]], #2] & @@@ b]
You can make b
into a list of rules
rules = {#, a__} :> {#, a, #2} & @@@ b;
and use it with ReplaceAll
:
a /. rules
{{1, 3, 5, 2}, {2, 6, 2, 1}, {3, 5, 6, 1, 2}, {4, 2, 3}}
or with Replace
:
Replace[a, rules, All]
{{1, 3, 5, 2}, {2, 6, 2, 1}, {3, 5, 6, 1, 2}, {4, 2, 3}}
This approach works for any ordering of the elements in the input list:
c = RandomSample[a]
{{2, 6, 2}, {3, 5, 6, 1, 2}, {1, 3, 5, 2}, {4, 2}}
c /. rules
{{1, 3, 5, 2}, {2, 6, 2, 1}, {3, 5, 6, 1, 2}, {4, 2, 3}}
Replace[c, rules, All]
{{2, 6, 2, 1}, {3, 5, 6, 1, 2}, {1, 3, 5, 2}, {4, 2, 3}}