4
$\begingroup$

I have a list:

lis = {{"a", "b", "X", "0"}, {"a", "f", "z", "1"}, {"g", "a", "z", "1"}, {"a", "b", "x", "0"}};

The last field of each element of lis is either "0" or "1".

I need to convert the third field in each element to upper case and then determine if there are any two elements in the list which have now become duplicates, delete the duplicate, and then change the last field of the remaining element from the deletion pair from "0" to "1" to get:

res = {{"a", "b", "X", "1"}, {"a", "f", "Z", "1"}, {"g", "a", "Z", "1"}}

Making the third field upper case and deleting duplicates is simple, but I'm not sure how to convert the last field from "0" to "1". Thanks for any suggestions...

$\endgroup$
  • $\begingroup$ It seems that DeleteDuplicates is useful here: DeleteDuplicates[MapAt[ToUpperCase, lis, {All, 3}]] /. "0" -> "1" $\endgroup$ – Αλέξανδρος Ζεγγ Jan 29 at 8:49
  • 2
    $\begingroup$ @ΑλέξανδροςΖεγγ this would break if one of the non-duplicates elements has "0" in its 4th index $\endgroup$ – Fraccalo Jan 29 at 8:50
5
$\begingroup$
First /@ 
 (GatherBy[MapAt[ToUpperCase, lis, {;;, 3}], Most] /. {{a__, "0"|"1"}, __} :> {{a, "1"}})

{{"a", "b", "X", "1"}, {"a", "f", "Z", "1"}, {"g", "a", "Z", "1"}}

Also

Tally[MapAt[ToUpperCase, lis, {;; , 3}], Most[#] == Most[#2] &] /. 
  {{a__, b_}, c_} :> {a, c /. {1 -> b, _ -> "1"}}

{{"a", "b", "X", "1"}, {"a", "f", "Z", "1"}, {"g", "a", "Z", "1"}}

and

SequenceReplace[Sort @ MapAt[ToUpperCase, lis, {;; , 3}], 
   {Repeated[{a__, _}, {2, ∞}]} :> {a, "1"}, ∞]

{{"a", "b", "X", "1"}, {"a", "f", "Z", "1"}, {"g", "a", "Z", "1"}}

$\endgroup$
3
$\begingroup$

This should also work:

#[[1]] /. {a_, b_, c_, _} :> {a, b, c, "1"} /; #[[2]] > 1 & /@ 
 Normal[Counts[MapAt[ToUpperCase, lis, {All, 3}]]]
$\endgroup$

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.