2
$\begingroup$

Coloring elements of sublists has been dealt with in another question.

A solution for sublists was presented along the following lines.

Permutations[{1, 2, 3}] // 
MapAt[Style[#, Red] &, #, {1, #} & /@ Range[2, 2]] & // 
MapAt[Style[#, Blue] &, #, {2, #} & /@ Range[3, 3]] &    

This produces the output of a list of permutations {{1,2,3},{1,3,2}, {3,2,1}}, in which the first sublist {1,2,3} has the element 2 (in position 2) colored red and the second sublist {1,3,2} has the element 2 (in position 3) colored blue.

I would like to obtain the result where all sublists have the second element colored red and the third colored blue.

This should be produced regardless of the number of sublists in the list.

$\endgroup$
3
$\begingroup$

Call the coloring function for each sublist using /@.

(MapAt[Style[#, Blue] &, MapAt[Style[#, Red] &, #, 2], 3] &) /@ Permutations[{1, 2, 3}]

result

$\endgroup$
3
$\begingroup$

Version 12 introduced SubsetMap which is a convenient generalization of MapAt:

SubsetMap[Thread[Style[#, {Red, Blue}]]&, #, {2, 3}]& /@ Permutations[{1, 2, 3}]

enter image description here

An alternative to SubsetMap and MapAt is to modify parts directly:

list = Permutations[{1, 2, 3}];
list[[All, {2, 3}]] = Thread[Style[#, {Red, Blue}]] & /@ list[[All, {2, 3}]];
list

same result

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.