3
$\begingroup$

I have a list like:

list1={{1, 16}, {1, 14}, {1, 3}, {1, 18}, {1, 2}, {1, 17}, {2, 17}, {2, 18}, {3, 14},{4,10}}

I would like to see if the first element of one nested list is an element of the first nested list and if so, append the second element of this list to the first list. Such that:

list2={{1, 16, 14, 3, 18, 2, 17}, {2, 17,...}, {3, 14,...},...}

My aim is to form a nested list of the chains of connected data. Any help at all would me much appreciated.

$\endgroup$
2
  • $\begingroup$ Shouldn't it be list2={{1, 16, 14, 3, 18, 2, 17, 2, 17,...}, {3, 14,...},...} because 2 was already part of the first list at that point? ` $\endgroup$ Commented Dec 8, 2017 at 15:42
  • 4
    $\begingroup$ Does GroupBy[list1, First -> Last] work for you? $\endgroup$
    – Carl Woll
    Commented Dec 8, 2017 at 15:51

3 Answers 3

3
$\begingroup$
KeyValueMap[## & @@@ {##} &] @ GroupBy[First -> Last] @ list1

{{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}}

$\endgroup$
1
  • $\begingroup$ Another (longer, but possibly more readable for people who don't like too many #s and @s) way using GroupBy is MapIndexed[Insert[#1, First@#2, 1] &, List @@ GroupBy[list1, First -> Last]]. $\endgroup$ Commented Dec 9, 2017 at 12:41
1
$\begingroup$

This would work:

DeleteDuplicates@Flatten@# &/@ GatherBy[list1, First]

(* {{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}} *)
$\endgroup$
2
  • 3
    $\begingroup$ You can use this without pure function DeleteDuplicates /@ Flatten /@ GatherBy[list1, First] $\endgroup$ Commented Dec 8, 2017 at 16:27
  • 1
    $\begingroup$ You can also Join instead of Flattening: DeleteDuplicates /@ Join @@@ GatherBy[list1, First]. $\endgroup$ Commented Dec 9, 2017 at 12:34
1
$\begingroup$
Rule @@@ list1 // Merge[#, Map@Sequence] & // KeyValueMap[List, #] & //
  Map[FlattenAt[#, -1] &]

{{1, 16, 14, 3, 18, 2, 17}, {2, 17, 18}, {3, 14}, {4, 10}}

$\endgroup$
1
  • 1
    $\begingroup$ Or shorter: KeyValueMap[Flatten@*List]@Merge[# &]@MapApply[Rule]@list1 $\endgroup$
    – eldo
    Commented Sep 8, 2023 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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