# Complicated double mapping over nested list

I have a list that each term consist of two parts. First part is a graph and second is a list of pairs of vertices that I want to find graph distance of.

list={{ImportString[">>graph6<<EK?_"],{{4,5},{2,6},{5,6}}},{ImportString[">>graph6<<HK?g_O?"],{{2,8},{7,8},{8,9}}},{ImportString[">>graph6<<KK?g_O@?_??C"],{{10,11},{10,12},{1,7}}}}


This means I want distances between vertices {4,5}, {2,6} and {5,6} of the first graph and so on...

I want the output in the form:

{{{{4,5},∞},{{2,6},2},{{5,6},∞}},{{{2,8},4},{{7,8},∞},{{8,9},∞}},{{{10,11},∞},{{10,12},∞},{{1,7},2}}}


I can map like GraphDistance[#[[1]],#[[2]]]&/@list but this does not work, of course, because it should be also mapped over #[[2]] like Sequence[#]&/@#[[2]]. I can not figure out how to double-map it.

• There are several different approaches you can take. One of them being: Map[d |-> ({{#[[1]], #[[2]]}, GraphDistance[d[[1]], #[[1]], #[[2]]]} & /@ d[[2]]), list] Commented Aug 23, 2022 at 9:59
• How di you do that? :-D It works, but I do not understand how it works. Commented Aug 23, 2022 at 10:09
• @Domen: Your code can be shortened to Map[d|->({#,GraphDistance[d[[1]],Sequence@@#]}&/@d[[2]]),list] Commented Aug 23, 2022 at 10:17

I'd say this is the most readable way to do it:

MapApply[
Function[{graph, vertices},
MapApply[
Function[{v1, v2}, {{v1, v2}, GraphDistance[graph, v1, v2]}],
vertices
]
],
list
]


Note that in versions lower than 13.1, you have to use Apply[f, list, {1}] instead of MapApply[f, list].

Based on @Domen's comment:

list={{ImportString[">>graph6<<EK?_"],{{4,5},{2,6},{5,6}}},{ImportString[">>graph6<<HK?g_O?"],{{2,8},{7,8},{8,9}}},{ImportString[">>graph6<<KK?g_O@?_??C"],{{10,11},{10,12},{1,7}}}};

(d|->{#,GraphDistance[d[[1]],Sequence@@#]}&/@d[[2]])/@list

Clear[list]

(* {{{{4,5},∞]},{{2,6},2},{{5,6},∞}},{{{2,8},4},{{7,8},∞},{{8,9},∞}},{{{10,11},∞},{{10,12},∞},{{1,7},2}}} *)


Using Thread:

Map[{#[[2]], GraphDistance[#[[1]], Sequence @@ #[[2]]]} &,
Thread[{#[[1]], #[[2]]}] & /@ list, {2}]

{{{{4, 5}, ∞}, {{2, 6}, 2}, {{5, 6}, ∞}}, {{{2, 8}, 4}, {{7, 8}, ∞}, {{8, 9}, ∞}}, {{{10,
11}, ∞}, {{10, 12}, ∞}, {{1, 7}, 2}}}