Group list elements using second list
lst1 = {"a", "b", "c", "d", "e", "f", "g"};
lst2 = {1, 2, 1, 2, 3, 3, 1};
Values@GroupBy[Thread[{lst1, lst2}], Last -> First]
(* {{"a", "c", "g"}, {"b", "d"}, {"e", "f"}} *)
list1 = {"a", "b", "c", "d", "e", "f", "g"};
list2 = {1, 2, 1, 2, 3, 3, 1};
Internal`PartitionRagged[list1[[Ordering @ list2]], Length /@ Gather @ list2]
{{"a", "c", "g"}, {"b", "d"}, {"e", "f"}}
Or
Map[First, #, {2}]& @ GatherBy[#, Last]& @ Transpose @ {list1, list2}
A timing comparison for all suggested methods which do not sort (Mathematica 11.0.0):
f1[{list_, labels_}] := Extract[list, Position[labels, #]] & /@ DeleteDuplicates@labels
f2[{list_, labels_}] := Pick[list, labels, #] & /@ DeleteDuplicates@labels
f3[{list_, labels_}] := Reap[MapThread[Sow, {list, labels}]][[2]]
f4[{list_, labels_}] := list[[#]] & /@ GatherBy[Range@Length@labels, labels[[#]] &]
f5[{list_, labels_}] := Values@GroupBy[Thread[{list, labels}], Last -> First]
f6[{list_, labels_}] := GatherBy[Transpose@{list, labels}, Last][[All, All, 1]]
f7[{list_, labels_}] := ReplaceList[#, Thread[labels -> list]] & /@ DeleteDuplicates@labels
f8[{list_, labels_}] := Map[First, #, {2}] &@GatherBy[#, Last] &@Transpose@{list, labels}
f9[{list_, labels_}] := Extract[list, List /@ GatherBy[Range@Length@list, labels[[#]] &]]
f10[{list_, labels_}] := Values@Merge[Association /@ Thread[Rule[labels, list]], Identity]
Needs["GeneralUtilities`"]
g[n_] := {RandomChoice[CharacterRange["a", "z"], n], RandomInteger[{1, n}, n]}
benchmarks = Benchmark[#, g, 10] & /@ {f1, f2, f3, f4, f5, f6, f7, f8, f9, f10};
For better readability I use a set of plot markers which tolerate overlapping from my PolygonPlotMarkers
package:
Needs["PolygonPlotMarkers`"]
ListLogLogPlot[benchmarks, ImageSize -> 600, BaseStyle -> FontSize -> 16, PlotMarkers -> {
Graphics[{FaceForm[Blue], EdgeForm[None], PolygonMarker["Circle", Offset[7]]}],
Graphics[{FaceForm[RGBColor[0.7, 0.745, 0.82]], EdgeForm[], PolygonMarker["Square", Offset[8]]}],
Graphics[{FaceForm[Green], EdgeForm[None], PolygonMarker["TripleCross", Offset[7]]}],
Graphics[{FaceForm[Red], EdgeForm[], PolygonMarker["FourPointedStar", Offset[9]]}],
Graphics[{FaceForm[Darker@Yellow], EdgeForm[None], PolygonMarker["DiagonalCross", Offset[7]]}],
Graphics[{FaceForm[], EdgeForm[{Brown, Opacity[1], AbsoluteThickness[2]}], PolygonMarker["DiagonalSquare", Offset[7]]}],
Graphics[{FaceForm[Cyan], EdgeForm[None], PolygonMarker["Square", Offset[7]]}],
Graphics[{FaceForm[Blue], EdgeForm[None], PolygonMarker["Cross", Offset[7]]}],
Graphics[{FaceForm[], EdgeForm[{Opacity[1], Black}], PolygonMarker["ThreePointedStar", Offset[7]]}],
Graphics[{FaceForm[], EdgeForm[{Opacity[1], Black}], PolygonMarker["Square", Offset[8]]}]},
PlotLegends -> PointLegend[{f1, f2, f3, f4, f5, f6, f7, f8, f9, f10}, LegendMarkerSize -> 15]]