4
$\begingroup$

Suppose I have a list as follows

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}}

and I want to check the last two coordinates are equal or not. If that is the case then I want it to print out T after that list. So the result should be

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1,T}}

I am thinking about using "if" but I have no idea how to do it.

$\endgroup$
2
  • 2
    $\begingroup$ Try: (Append[#, If[#[[-1]] == #[[2]], "T", Nothing]]) & /@ {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}} $\endgroup$ May 11, 2022 at 9:13
  • $\begingroup$ Yes, you are right! Thank you. $\endgroup$ May 11, 2022 at 19:40

4 Answers 4

5
$\begingroup$

I think the most expressive would be to use Replace:

list = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};
Replace[
  list, 
  {rest___, l_, l_} :> {rest, l, l, T},
  1
]
(* {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}} *)

Some alternatives:

Replace[list, list : {___, l_, l_} :> Append[list, T], 1]
Replace[list, l_ /; Equal @@ l[[-2 ;;]] :> Append[l, T], 1]
Replace[list, {list : PatternSequence[___, l_, l_]} :> {list, T}, 1]
Map[If[Equal @@ #[[-2 ;;]], Append[#, T], #] &, list]
Map[If[#[[-2]] == #[[-1]], Append[#, T], #] &, list]
Map[If[Equal @@ #[[-2 ;;]], Append[T], # &]@# &, list]
$\endgroup$
2
$\begingroup$
alist = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}}

Join @@@ Transpose[{#, 
      List /@ Equal @@@ #[[All, -2 ;; -1]]}] /. {False -> Nothing, 
    True -> T} & @alist

A simpler version of the above:

# ~ Join ~ If[Equal @@ #[[-2 ;; -1]], {T}, {Nothing}] & /@ alist

Description: Take a sublist (#) and Join an item with it. The item will be T if the last two entries are Equal, else Nothing. Map (/@) this over the entire list.


Result:

{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}
$\endgroup$
1
$\begingroup$

Another way:

 A = {{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1}};
 Map[If[Mean[#[[-Length[#] ;; -(Length[#] - 1)]]] === Last[#], Append[#, T], #] &, A]
 (*{{1, 1, 1, 1, 1, 3}, {1, 1, 3, 4, 1, 1, T}}*)
$\endgroup$
1
$\begingroup$

If your data is always a list of lists and you always want the transformation performed at that second level, then this works (I've named your data theData):

Replace[theData, {head___, t_, t_} :> {head, t, t, "T"}, 1]
$\endgroup$

Your Answer

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

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