5
$\begingroup$

If i have a

list={m,n,p,q,q,r,l,l}

how can i remove the repeated item with pattern matching so i would have

modifiedlist={m,n,p,r}?
$\endgroup$
7
$\begingroup$
Keys@Select[Counts[list], # == 1 &]

{m, n, p, r}

Also:

Select[list, Count[list, #] == 1 &]
Select[list, Counts[list][#] == 1 &]
Flatten[Cases[Split[Sort[list]], {_}]]
Flatten[DeleteCases[Split[Sort[list]], {_, __}]]
Flatten[Select[Split[Sort[list]], Length@# == 1 &]]
SequenceReplace[list, {OrderlessPatternSequence[Repeated[b_, {2, Infinity}], a_]} :> a]
| improve this answer | |
$\endgroup$
  • $\begingroup$ very nice i added {m,n,p,q,q,r,l,l} /. a_List :> Select[a, Count[a, #] == 1 &] $\endgroup$ – user49047 Jan 23 '19 at 12:26
  • $\begingroup$ @user49047, Select[a, Count[a, #] == 1 &] gives you the result directly; you don't need to use ReplaceAll. $\endgroup$ – kglr Jan 23 '19 at 12:30
  • $\begingroup$ The method using Counts is probably the best way, since you only have to traverse the whole list once. $\endgroup$ – Sjoerd Smit Jan 23 '19 at 12:41
  • $\begingroup$ @SjoerdSmit, excellent point. $\endgroup$ – kglr Jan 23 '19 at 12:43
6
$\begingroup$
First /@ Select[Tally@list, Last@# == 1 &]

{m, n, p, r}

or

First /@ Cases[Tally@list, {_, 1}]

{m, n, p, r}

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Cases[] seems to be fastest so far on large lists. Cases[Tally@list, {_, 1}][[All, 1]] is about 10% faster on unpacked arrays, slightly slower on packed arrays. $\endgroup$ – Michael E2 Jan 23 '19 at 12:58

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.