Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by kglr for Adding elements to some sublists of unequal length

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}}


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>