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$
  • $\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$ – Thies Heidecke Dec 8 '17 at 15:42
  • 2
    $\begingroup$ Does GroupBy[list1, First -> Last] work for you? $\endgroup$ – Carl Woll Dec 8 '17 at 15:51
3
$\begingroup$
KeyValueMap[## & @@@ {##} &] @ GroupBy[First -> Last] @ list1

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

$\endgroup$
  • $\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$ – aardvark2012 Dec 9 '17 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$
  • 3
    $\begingroup$ You can use this without pure function DeleteDuplicates /@ Flatten /@ GatherBy[list1, First] $\endgroup$ – Okkes Dulgerci Dec 8 '17 at 16:27
  • 1
    $\begingroup$ You can also Join instead of Flattening: DeleteDuplicates /@ Join @@@ GatherBy[list1, First]. $\endgroup$ – aardvark2012 Dec 9 '17 at 12:34

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.